Groovy calling CountDownLatch.await() lead to hang - groovy

I'm new to groovy and have this simple code snippet:
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
CountDownLatch called = new CountDownLatch(1)
Timer timer = new Timer()
timer.schedule(new TimerTask() {
void run() {
called.countDown()
}
}, 0)
assert called.await(2, TimeUnit.SECONDS)
Upon running on command line, it just hang there, nothing happen. I expect that this program should quit at once. So where did I get wrong?

Actually, it's not await that leads to hanging in your case. It's just the Timer's thread is not a daemon. The JVM cannot terminate until all remaining running threads are daemons. As Thread#setDaemon() javadoc states it:
...The Java Virtual Machine exits when the only threads running are all daemon threads.
So in your case
You can just specify that the timer's thread is a daemon
CountDownLatch called = new CountDownLatch(1)
Timer timer = new Timer(true) //true means the underlying thread is a daemon
timer.schedule(new TimerTask() {
void run() {
called.countDown()
}
}, 0)
assert called.await(2, TimeUnit.SECONDS)
println("It's not await that leads to hanging")
Or if for some reason you don't want your timer's thread to be a daemon. E.g. you want the timer to handle all the scheduled tasks before the JVM terminates. In this case you can just cancel the timer at some appropriate moment
CountDownLatch called = new CountDownLatch(1)
Timer timer = new Timer() //now the underlying thread is NOT a daemon
timer.schedule(new TimerTask() {
void run() {
called.countDown()
}
}, 0)
assert called.await(2, TimeUnit.SECONDS)
println("It's not await that leads to hanging")
timer.cancel()//now we are done. All scheduled tasks will be cancelled. However, the running one will finish its job
P.S. If you want more flexible way of scheduling you can take a look at ScheduledThreadPoolExecutor. As Timers javadoc says:
...It is effectively a more versatile replacement for the Timer/TimerTask combination, as it allows multiple service threads, accepts various time units, and doesn't require subclassing TimerTask (just implement Runnable). Configuring ScheduledThreadPoolExecutor with one thread makes it equivalent to Timer.

Related

What is the purpose of await() in CountDownLatch?

I have the following program, where I am using java.util.concurrent.CountDownLatch and without using await() method it's working fine.
I am new to concurrency and want to know the purpose of await(). In CyclicBarrier I can understand why await() is needed, but why in CountDownLatch?
Class CountDownLatchSimple:
public static void main(String args[]) {
CountDownLatch latch = new CountDownLatch(3);
Thread one = new Thread(new Runner(latch),"one");
Thread two = new Thread(new Runner(latch), "two");
Thread three = new Thread(new Runner(latch), "three");
// Starting all the threads
one.start(); two.start(); three.start();
}
Class Runner implements Runnable:
CountDownLatch latch;
public Runner(CountDownLatch latch) {
this.latch = latch;
}
#Override
public void run() {
System.out.println(Thread.currentThread().getName()+" is Waiting.");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
latch.countDown();
System.out.println(Thread.currentThread().getName()+" is Completed.");
}
OUTPUT
two is Waiting.
three is Waiting.
one is Waiting.
one is Completed.
two is Completed.
three is Completed.
CountDownLatch is the synchronization primitive which is used to wait for all threads completing some action.
Each of the thread is supposed to mark the work done by calling countDown() method. The one who waits for the action to be completed should call await() method. This will wait indefinitely until all threads mark the work as processed, by calling the countDown(). The main thread can then continue by processing the worker's results for example.
So in your example it would make sense to call await() at the end of main() method:
latch.await();
Note: there are many other use cases of course, they don't need to be threads but whatever that runs usually asynchronously, the same latch can be decremented several times by the same task etc. The above describes just one common use case for CountDownLatch.

ThreadPoolExecutor is not executing concurrently?

This is for my academic purpose only. Are the tasks that we add to the executor service are really executing in parallel. Well this is my example that raised this question
Runnable Class
public Tasks implement Runnable{
int taskCount;
public Tasks(int count){
this.taskCount = count;
}
public void run(){
System.out.println("In Task :"+taskcount +" run method");
}
}
Main Class
Class MyTest {
public static void main(String args[]){
ExecutorService service = Executors.newFixedThreadPool(10);
for(inti=0;i<10;i++){
Tasks taskObj = new Tasks(i);
service.submit(taskObj);
}
service.shutdown();
}
}
As soon as i submit a taskObj to the executor, the taskObj run() is invoked.
What if i have to something like this,
Add all the taskObj to the executor , the run() must not get invoked
Execute all the task objects at one shot. All the taskobj run() must be executed in parallel/concurrently
Please let me know
Thanks...V
If I understood you right, one way to solve this would be to use thread barriers. This might sound strange, but is actually implemented quite easy. You just take a variable (lets name it traffic-light) and make every thread loop on it. If you started enough threads (starting a new thread might consume some time) you just change it to green and all your threads will start execution at the same time.
For academic purposes we used to take an atomic-integer as counter (initialized with 0) and started n threads. The task of each threads was to increase the counter and then loop on it until it reached n. Like this you'll have all threads as parallel as possible.
If you still want to go with a thread pool system, you might have to implement your own thread system, where threads can wait upon a signal prior to grabbing work.
good luck

How to run a function after a specific time

I want to as if there is any way to execute a function after a specific time in windows phone 7.? For instance, see this code in android:
mRunnable=new Runnable()
{
#Override
public void run()
{
// some work done
}
now another function
public void otherfunction()
{
mHandler.postDelayed(mRunnable,15*1000);
}
Now the work done in upper code will be executed after 15 seconds of execution of otherfunction().
And I want to know is this possible in any way in windows phone 7 also.?
Thanx to all in advance..
Although you can use the Reactive Extensions if you want, there's really no need. You can do this with a Timer:
// at class scope
private System.Threading.Timer myTimer = null;
void SomeMethod()
{
// Creates a one-shot timer that will fire after 15 seconds.
// The last parameter (-1 milliseconds) means that the timer won't fire again.
// The Run method will be executed when the timer fires.
myTimer = new Timer(() =>
{
Run();
}, null, TimeSpan.FromSeconds(15), TimeSpan.FromMilliseconds(-1));
}
Note that the Run method is executed on a thread pool thread. If you need to modify the UI, you'll have to use the Dispatcher.
This method is preferred over creating a thread that does nothing but wait. A timer uses very few system resources. Only when the timer fires is a thread created. A sleeping thread, on the other hand, takes up considerably more system resources.
You can do that by using threads:
var thread = new Thread(() =>
{
Thread.Sleep(15 * 1000);
Run();
});
thread.Start();
This way, the Run method wil be executed 15 seconds later.
No need for creating threads. This can be done much more easier using Reactive Extensions (reference Microsoft.Phone.Reactive):
Observable.Timer(TimeSpan.FromSeconds(15)).Subscribe(_=>{
//code to be executed after two seconds
});
Beware that the code will not be executed on the UI thread so you may need to use the Dispatcher.

WCF InstanceContextMode.PerCall Services and Multi-Threading

I am running a self-hosted WCF Service (it will be a Windows Service but I'm runnning it as a Console App for debugging). The server side code needs to do some work when it is called. Then pass back the result synchronously to the client. It then needs to carry on and do some more intensive long-running processing.(ie asynchronously)
A simplified illustration of the code is :
[ServiceBehavior(IncludeExceptionDetailInFaults = true,InstanceContextMode = InstanceContextMode.PerCall)]
public class MyWCFService : IMyWCFService, IDisposable {
private Thread importThread;
private DoWork importWork;
public MyImportResultContract StartImport(MyImportRequestContract requestParams) {
processorResult = new MyImportResultContract();
//Simulate a short piece of work here to return results to the
//caller before calling a Thread to do more processing
processorResult.Success = true;
processorResult.Messages = "A message to pass back to caller"
Console.WriteLine("WCF Class ManagedThreadId = " + Thread.CurrentThread.ManagedThreadId);
//Thread off to do long running process
importWork = new DoWork();
importThread = new Thread(importWork.Start);
importThread.Start();
//Pass back the results
return processorResult;
}
public void Dispose() {
Console.WriteLine("WCF Class Dispose : " + DateTime.Now.ToLongTimeString());
}
}
internal class DoWork : IDisposable {
public void Start() {
Console.WriteLine("Thread ManagedThreadId = " + Thread.CurrentThread.ManagedThreadId);
//Simulate a long running process
Thread.Sleep(60000);
Console.WriteLine("Thread Finished");
}
public void Dispose() {
Console.WriteLine("DoWork Class Dispose : " + DateTime.Now.ToLongTimeString());
}
}
I have 2 questions:
1. I'm seeing the Dispose of the Service Class called before the Thread it spawns carries on and completes. My concern is that the Service class instance might not be getting released for Garbage collection because of the thread it spawns. Is the code outlined here solid so that this won't happen?
2. The service is self hosted in a Windows Service. What will happen if the service is stopped to any spawned threads ? Is there a way to get the service to wait until any Threads still running complete ?
Of course the service class can be disposed before the thread completes. If you wanted to wait for the work in the thread to complete, why start a thread? I'm not sure what behavior you expect/want other than this.
Yes, if the process is shut down your threads die. You have to implement a handler for the service stop callback which delays the shutdown process until all workers are complete. This will be easier to do if you use the more modern Task instead of Thread. Probably, you need to keep a global list of tasks in process so that your shutdown code can WaitAll on those tasks.

Pause a QThread

UpdateThread is-a QThread That sets up a QTimer in UpdateThread::run() that calls slot UpdateThread::tick() every t ms. Now based upon some condition I need to Pause the Thread and after some time based upon another condition I need to wake it up.
Is the Way I am doing the QTimer thing is Okay ? or I should move the tick code to run and call the QThread::start() every t ms ?
How can I Pause and wake up the threads conditionally
Or I should just stop() the QTimer and start() it latter ?
First of all, you shouldn't define slots on your QThread subclass and call them from within run() - the slots will be executed (by performing a cross-thread slot invocation) in the context of the thread that owns your UpdateThread instance (the same one that created it, unless you called moveToThread() on it), not in the context of the thread represented by UpdateThread. Remember this mnemonic:
In run(), QThread::thread() != this
Instead, define the slots on a QObject subclass that you create inside run().
Ok, with that out of the way, let's have a look at the timer. The QTimer documentation contains the following:
In multithreaded applications, you can use QTimer in any thread that has an event loop.
To start an event loop from a non-GUI thread, use QThread::exec(). Qt uses the timer's
thread affinity to determine which thread will emit the timeout() signal.
Because of this, you must start and stop the timer in its thread; it is not possible to
start a timer from another thread.
(emphasis mine) Take particular note of the last sentence.
The solution is to do a cross-thread call of QTimer::start() and QTimer::stop(). You might know about cross-thread signal/slot connections. This uses the same underlying mechanism, which is exposed in QMetaObject::invokeMethod():
class UpdateThread : public QThread {
Q_OBJECT
private:
QObject * m_timer; // just a QObject* so we're not tempted
// to call functions on it
QMutext m_mutex; // protects 'm_timer'
public:
explicit UpdateThread( QObject * parent=0 )
: QThread( parent ), m_timer( 0 ) {}
// ...
private:
/* reimpl */ void run() {
QTimer timer;
// ...'timer' setup code goes here...
{
const QMutexLocker locker( &m_mutex );
m_timer = &timer; // publish 'timer' through 'm_timer'
}
// main code of run()
exec(); // start event loop so we get timer's timeout()s
// and we can receive cross-thread method calls
{
const QMutexLocker locker( &m_mutex );
m_timer = 0; // un-publish before we delete `timer`
}
}
public Q_SLOTS:
void startTimer() {
const QMutexLocker locker( &m_mutex );
if ( !m_timer ) return;
// perform cross-thread method call:
QMetaObject::invokeMethod( m_timer, "start", Qt::QueuedConnection );
}
void stopTimer() {
const QMutexLocker locker( &m_mutex );
if ( !m_timer ) return;
// perform cross-thread method call:
QMetaObject::invokeMethod( m_timer, "stop", Qt::QueuedConnection );
}
};
Now, this is how you start/stop the timer from the GUI thread. But you were also asking about alternatives.
Move tick() code into run(), call UpdateThread::start() every t milliseconds.
This is suboptimal, as it would create and destroy threads every t ms. Thread creation is still an expensive operation. Also, if UpdateThread::run() isn't done by the time you next call start(), you'll lose timer ticks.
UpdateThread as outlined above.
This isn't too bad, but it's not idiomatic multithreading, I'd say. It's a good solution if the timer fires so often that that alone would slow down the GUI thread somehow, though you might lose timer ticks this way, too.
QThreadPool
My favourite. Move the code that performs tick() into an implementation of QRunnable::run(), and queue a new runnable on a thread pool whenever the timer fires. In this case, the timer would most naturally live in the GUI thread, avoiding the need for cross-thead method calls as outlined above. Unless the GUI thread itself is overloaded, you won't miss any timer ticks. You also get for free scaling to the number of cores in the system (if you don't want that, don't use QThreadPool::globalInstance() but create your own instance and call setMaxThreadCount(1)).

Resources