java threads : producer - consumer - java

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.

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.

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

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.

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.

How to set a flag to indicate when all threads are done running

I was wondering if anyone had information regarding how to set a flag to indicate when all the threads are done running?
I have 7 threads that run concurrently but I need to set a flag to show when all of them are finished to run a method to update the database table so it can switch to the other service. This is the first time I am using threads so if anyone could point me in the right direction that would be great.
You can try with CountDownLatch. It will full fill your requirement, What you have to do is, create an instance of CountDownLatch with count value equal to the number of threads. Start all the thread and call await method in main thread. Have the CountDownLatch object reference in all the threads and call the countDown method in each thread after completing its own job. For each countDown method, the CountDownLatch count value will get decrement. Once it reaches to zero the method where await is called will get wake-up. Note if any one of your thread fails to call countDown then await will never get wake-up.
Try this for your reference,
http://www.java-redefined.com/p/java-count.html
Use the join method to wait for each thread to finish execution.
for (Thread t : threads) {
t.join();
}
If you're using threads directly, check out CountDownLatch. Depending on how complex your workflow is, you may prefer the Phaser.

How do I schedule a print statement upon completion of 4 independent threads?

I have a simple java application which calculates prime numbers up to a certain user-given number and prints out the numbers. I've built upon this to include four separate threads which iterate through 4 separate ranges of numbers. Once all 4 threads have completed their iterations I want to print the final ArrayList.
I'm currently getting a ConcurrentModificationException because after I start the 4 threads, the next line of code is the print statement which is trying to print the ArrayList which is at that moment being modified by at least one of the still active threads.
Therefore, I want to be able to have the print statement execute after all 4 threads have died. Furthermore, I would like to do this without using a spinning loop. I have nothing in particular against using a spinning loop except that I imagine there is a better way to do this and I would probably have to assign greater priorities to the 4 threads in order to prevent the spinning loop from using up a significant amount of the CPU.
Use a CountDownLatch initialized to 4; the print thread awaits the latch, and the worker threads call countdown on the latch before they terminate.
Be sure to properly synchronize your ArrayList as well if four threads are modifying it at once; you may want to use a ConcurrentLinkedQueue instead (or else use a different ArrayList for each thread)
Use a CountdownLatch. The Javadoc for that class tells how to have
The main thread creates the latch with the number of threads.
The main thread starts all the working threads.
Each thread has a reference to the latch.
It counts the latch down when it finishes its work.
The main thread waits for the latch to count down to 0.
The main thread does the printing job.
If you use a java.util.concurrent.BlockingQueue, each thread could put() an item on the blocking queue when it is finished.
Before the print statement, the code could do a take() from the blocking queue and only proceed when the take() has returned once for each thread. The printing thread will block on the take() while there is nothing there for it to take. That will guarantee that the printing doesn't commence until all the threads have finished.

Categories

Resources