do ExecutorService and CountDownLatch block the main thread till they finish? - java

My problem is, I have two threads t1 and t2. Both of them make some calculations, and according to my program, I want to use a concurrency technique that blocks till t1 and t2 both finish their tasks and then continue.
I tried countdownLatch, and I read about ExecutorService and made a small example. Concerning the ExecutorService I did something like the following:
executor.execute(new RunnableClass(bgr,3))
executor.execute(new RunnableClass(bgr,7))
executor.shutdown();
if (executor.isTerminated()) {
print("terminated")
}
and the word "terminated" was never printed, which means executorService object does not block.
please let meknow whih concurrency technique i should use to suit my situation

Reading the documentation is always going to clarify things before you start coding..
But just wanted to share a few points :
1.) CountDownLatch can be a solution for your problem. Read this link before you code..
http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CountDownLatch.html
Basically the concept is that you have latch your program in a fixed state and stop it from proceeding until the latch is released.
So you have 2 threads...set a countdownlatch value of 2. Make both the threads decrement the value after they are done. Till the latch value is decremented to 0 the main thread will be waiting for this to take place.
executor.shutdown....refer documentation...it says that it waits for all submitted tasks to complete before it shutsdown.

Related

ExecutorService awaitTermination method vs using CountDownLatch

So I'm still a bit new to multithreading and came across these two classes. What I understood is that an ExecutorService can be a thread pool and via the awaitTermination method the thread in which it is called comes to a halt until the threads in the thread pool have finished running.
Then there is the CountDownLatch you can give to your Runnables. These can then in turn call the countDown() method. If you then use the await() method in your main thread, this thread will come to a halt until the countdown has reached zero.
I don't seem to spot the difference in result between the two ways? Why would I ever use a CountdownLatch?
There are lots of different things where you might want to wait for lots of things to be processed that don't involve shutting down your thread pool.
For example you might have 5 servers that you are monitoring, with a thread to monitor each one. A Countdown Latch is used to fire off another thread once all the first 5 have connected.
It can also be used in many other situations, for example if you have some initialization to happen then all the threads may wait on the countdown latch until all the initialization has finished and the latch is counted down to zero.

Main thread wait for other threads

After seaching a lot and not finding a concrete answer
If I have two threads started:
Thread t1 = new Thread();
Thread t2 = new Thread();
t1.start();
t2.start();
After starting the threads I need the main thread to wait for these two thread to finish before printing the final result
How can I make the main thread wait for both t1 and t2?
A plain wait() would be enough?
Add
t1.join();
t2.join();
in your thread which should wait till t1 and t2 will finish their tasks (in your case call it from your main thread).
The answer depends...
You could
Use a CountDownLatch which is probably the simplest solution.
This way you would simply wait on the latch until it has been signaled the prescribed number of times (by each Thread terminating). This scales quite nicely as you increase the number of threads...
You could
Use join, but it would become tedious as you add more threads
You could
Add each Thread to a List, loop through the list, removing those threads that are no longer alive and keep looping until the List is empty, but that's a rather heavy handed approach.
You could
Combine the above solution with some kind of monitor lock which the loop would wait on and each Thread would notify when they complete, but it's not much cleaner and you could still end up waiting for non-existent threads...
You could
Use an ExecutorService and either use it's invokeAll and/or shutdown methods. See Executors for more details. This also scales quite nicely and even has the added benefit of allowing you to use a Thread pool to better manage the system resourcs
Check out the Thread#join method.
Also, you might find using an ExecutorService (and friends) helpful. Its essentially thread pool/management and provides a lot of conveniences and IMO a cleaner API than threads. Barrier to entry is low...
You want Thread#join(). wait() is for signalling, join() is to wait for the thread to finish.

What is the difference between join and CountDownLatch?

When waiting for other threads to finish, we can use either join or CountdownLatch. What are the pros and cons of using either of those two mechanisms?
You can only use Thread.join if you're handling the threads yourself. Most people choose not to deal with the minutia of thread handling directly, and instead use an ExecutorService to handle it for them. ExecutorServices do not directly reveal how they are executing tasks, so you would have to use a CountDownLatch: (Assuming you don't want to just shutdown the whole service, that is.)
ExecutorService service = Executors.newFixedThreadPool(5);
final CountDownLatch latch = new CountDownLatch(5);
for(int x = 0; x < 5; x++) {
service.submit(new Runnable() {
public void run() {
// do something
latch.countDown();
}
});
}
latch.await();
Another difference is after join(), thread can be unblocked only when joined thread has finished its execution while in CountDownLatch a thread can decrease the count anytime either on completion of thread or in between based on any condition.
This way we can get better control over unblocking of the thread instead of solely depending on the completion of joined thread.
join() is waiting for another thread to finish while CountDownLatch is designed for another purpose. If using CountDownLatch, You don't have to have reference of threads for which you are waiting as we have to do using join(). Let's assume you want to start a game when at least 2 players should be available. You can use countdownlatch in this case. But you can't achieve this using join easily because you don't have another thread(player in this case) on which you can write join().
A CountdownLatch is task-oriented - it's thread-agnostic. A whole pile of unrelated sets of tasks can be submitted to a threadPool and a CountdownLatch will ensure that each set notifies the originator of completion. Join() is an annoying abberation that links tasks to threads and, simply put, should never have entered the language in the first place. Sadly, a large, steaming pile of thread-tutorials mention Join() on the first page, thereby introducing threads to newbies as a deadlock-generator and generating thread-funk :(
CountdownLatchallows you to change the implementation of Item to maybe submit to an Executor service instead of using Threads directly.
The CountDownLatch class allows us to coordinate the starting and stopping of threads. Typical uses are as follows:
We can make several threads start at the same time;
We can wait for
several threads to finish (whereas, for example, the Thread.join()
method only lets you wait for a single thread).
You can have a look at this -> http://javahowto.blogspot.com/2011/08/when-to-join-threads-with.html
And this ->
A CountDownLatch's latch.await() method vs Thread.join()

java threads : producer - consumer

I have some developpements to do and I try to see if there is a desing pattern to use.
The problem is simple:
I have a main thread that launches many treads. The main thread must wait for each thread to finish and then doing something else.
The existing code it's a bit ugly. I have a while loop that check a thread group to see if is something running:
//launch threads
.....
//wait for threads to finish
while (ThreadRepository.getInstance().isActiveThreadGroup(myGroupId)) {
Thread.sleep(5000);
}
//doing something else
So, as you see, the while loop keeps running until no threads running.
I was thinking at the pattern producer-consumer and I would like to do something like that:
Using some BlockingQueue for instance, and each thread put (or take) something in it.
Instead of having the while and sleep I would like to have something like
myQueue.take() but something to wait for the queue to be empty.
When empty, it means no threads running.
I try to search on the Internet but I did not found something that matches my problem.
Does anyone know the most efficient to solve my problem ?
There are two easy ways to have one thread wait for N threads to finish:
Make the main thread call join() on all the other threads. join() returns when a thread finishes, or has already finished
Create a CountDownLatch initialized to N, pass this latch to all the threads, make each thread call countDown() on the latch when it has finished, and make the main thread call await() on the latch. This second technique is a bit harder than the first one, but is also more flexible and reusable, and allows being awaken after some delay, even if the N threads have not finished yet.
You can use BlockingQueue as follows:
each child thread puts a message in the queue when finished
the main thread takes messages from the queue and counts them. When the number of messages equals the number of threads, all threads has finished.

CountdownLatch combine await(maxTime) and countdown()

I have several threads running for an almost infinite time and number of iteration. The iteration count being reset to 0 when a best solution has been found. A max number of iteration is set to prevent an infinite loop.
I use a countdownlatch to stop the process when all thread have reach the max number of iteration. In other word, when a thread reach the max number of iteration, it notifies my main thread using notifyThreadStop() which, when all thread are stopped, triggers countdown().
Note: my threads are running inside a FixedThreadPool ExecutorService.
I would like to add a maxTime latch. So what i did is the following
List<Runnable> r = .... //(contains all my runnables)
myExecutorService.invokeAll(r);
if(maxtime > 0){
mylatch.await(maxTime,TimeUnit.Seconds);
(1)
do stuff...
exit;
}
else{
mylatch.await();
myExecutorService.shutdownNow();
do stuff...
exit;
}
Now, I know that if the countdown has triggered the latch, it means that all threads are stopped so I can shutdownNow my ExecutorService.
It is not the case when the max time has been reached. So in (1) i would like to iterate through all my runners to terminate them in a civilized way :-) . For that, i have defined a function requestTermination() that, simply put, set the iterationCounter to MaxIterationCount in my runnables.
So (1) would become
for(Runnable runner: r){
if(r.getIsRunning()){r.requestTermination();}
}
(2)
Now, I need to wait again until all threads are really stopped before i can proceed.... hmmmm just thinking that i could have an additional latch and work with that.
So (2) would become
mylatch2.await();
myExecutorService.shutdownNow();
Of course, my function notifyThreadStop() would need to be modified of it and would need a flag telling it to do a countdown() on mylatch2 as opposed to mylatch.
I think I have just answered my question but since all this has been written, I'll leave it here for others to refer to it.
The question would now be: Any better way of handling this? Would a shutdownNow() in (1) or (2) be the only thing required? Knowing that my my threads have to close their own log file and shutdown their inner Callable thread*ss* before exiting.
If you use shutdownNow() and awaitTernimation() this will interrupt all running tasks and wait for them to finish.
Provided the tasks can be interuppted and close all resources correct when interrupt, there shouldn't be a problem. (If there is a problem, this is a bug in your task code which you should fix)
I think I have just answered my question but since all this has been written
You did, indeed :-) If there's one thing to add is that you should be careful with RuntimeExceptions, otherwise, your shutdownNow() may never be called. But you knew that already, right?

Categories

Resources