I'm learning executor service in java.
Requirement is using executor service create 4 threads -
Thread 1 - get two numbers as input.
Thread 2 - addition of two numbers
Thread 3 - multiplication of two numbers
Thread 4 - print the results.
Thread 1 should be executed first, after thread 1 is complete thread 2, 3 can start processing simultaneously and finally once thread 2, 3 is completed. Thread 4 should run finally.
How can we make sure which thread starts first and which threads to start simultaneously next. Finally which thread to execute at last.
Note: How can we achieve this without using thread sleep. Dynamically as soon as thread 1 finishes other two threads should start automatically.
First, Read my comment on your original question--the one about using a car to hammer in nails.
Ok, Now, #dan1st had some ideas about how to structure the solution. Here's two more.
Use a global int variable, a global lock, and wait() and notifyAll(): Have each thread enter a synchronized(lock) block in which it
Loops, calling lock.wait() until the global int has some particular value,
Does its trick,
Sets the global int to the value that will trigger the next thread,
calls lock.notify(), and finally
exits
Use Semaphores: Pass two Semaphore instances in to each thread. Call them in and out or some such names. Have each thread
wait its turn by calling in.acquire(),
do its trick,
call out.release(),
and then exit.
Your main routine then is responsible for creating the semaphores, and passing them to the new threads in such a way that each thread's out refers to the same semaphore as the in of the thread that is expected to perform the subsequent task.
IMO, option 2 is more elegant, because if your teacher asks you next week to modify your program by adding another step in the middle of the sequence, then none of the existing tasks that you wrote will have to change at all. You'll only need to write the new task and change two or three lines in the main() routine.
Doesn't sound like much of an improvement, and option 2 clearly is more work to set up in the first place than option 1, but if you ever are employed to work on enterprise-scale software systems with millions of lines of code, you will come to appreciate the beauty of option 2.
You could do this using multiple ways.
For exanple, joining:
A Thread can join another Thread, which means that it waits until the other Thread finishes. Thread 2 and 3 could join Thread 1 and Thread 4 could join Thread 2 and 3.
Another possibility is await and signal but I am not sure if it meets your Requirements(it uses something similar to Thread.sleep():
At first, you create a common java.util.concurrent.locks.Lock and create a condition of this lock with .newCondition() You also create a second condition using newCondition().
The lock has to be locked before calling await and signal/signalAll.
Thread 2 and 3 calls .await() on the first condition before starting and Thread 1 calls .signalAll on the first condition when it finishes.
Thread 4 calls .await() on the second condition before it starts.
The Thread (either 2 or 3) that finishes last(the logic which Thread finished first should be synchronized with the lock) calls .signal() on the second condition.
The threads could also start each other:
Thread 1 starts Thread 2 and 3 after it's task finishes but I would recommand you one of the other mechanisms for Thread 4.
[DISCLAIMER]
You may not be able to interact with the Threads directly if you use an ExecutorService. This post might help you with joining, await/signal should not be more difficult and the Threads can also schedule a task to the thread pool if needed.
Related
In my main method i have started 1 daemon thread which runs in background to check certain condition is satisfied, if satisfied then my main thread should wait for sometime and then continue.
Is it possible to do so? Controlling Main thread from another thread.
Actually am trying to automate 1 application where there are many pop-up windows displayed and I want to use 1 thread in background to check for pop-ups, if pop-ups are displayed then my main method should wait for some time then begin again.
You can simply use the wait() and notify() on a common lock object.
From inside the main method, syncronize on the lock object. Within the synchronized block start your another thread and invoke wait() on the lock object.
In the run method of your second thread , write a synchronized block on the lock object and do your processing. Once it is done you can invoke the notify on the same lock object.
Main thread can then check if the required state has been set and then further actions can be decided (if you wish the main thread to complete its execution further or again wait and let second thread again do the processing) If you wish the second thread to again do (retry) the processing then like above you can invoke the notify() on the lock object and then can then invoke wait() on the same lock object.
This is the usual way of communication between two threads. But if its only single time process and you do not want it to happen multiple times then you can simply use the join() method. Main thread can join on the second thread. Till the second thread will be processing its task the main thread will be waiting for the processing to complete. Once the second thread is executed completely (end of run () method) control will reach the maim thread.
I suggest you to have a look at these methods. consumer-producer is a famous problem to understand these methods. You can also see these in action in an answer to another post.
https://stackoverflow.com/a/42049397/504133
My application will, during runtime, contain multiple threads (in this example 7) doing independent work. However, every once in a while, the threads will have to synchronize their data.
This will be done by the threads calling the DataSynchronizer object which they all have a reference to.
My idea for flow in this class looks like this:
public class DataSynchronizer {
public void synchronizeData(List<Data> threadData) {
// Wait for all 7 threads to call this method
// When all 7 are here, hold them here & do work using one of the threads
// or a new anonymous thread
// Release the threads & let them continue their independent work
}
}
My question is, what is the best way for me to 'wait for all x threads' before doing the synch work?
I know that all threads will call the synchronizeData method within 1, max 2 seconds of each other.
So do I,
1) Wait for 2s after the first thread call the method and assume all threads have now also arrived? or
2) Keep a count to make sure all active threads have arrived? (App will wait for eternity if a thread crashes just before calling method)
3) Count + timeout?
4) ???
This is what a CyclicBarrier is for. It allows you to define spots where threads will wait until all arrive, and then optionally run a Runnable to perform synchronization or other such thing.
I think you need a java.util.concurrent.CyclicBarrier.
Assume and threads is a very risky approach.
How bad is waiting for an eternity? Sounds inconvenient to me.
If you hit the timeout can you do something useful? Crash the program, restart the errant thread, assume something about what it is doing?
Follow-on questions:
What happens if a thread doesn't participate in the synchronisation?
What happens if the sync is late?
Should your method tell one thread from another, or are they just 7 interchangeable workers?
There are 3 threads: Main Thread (thread from which main() runs on), Thread A and Thread B.
Order of Operations:
Program Starts (main())
Main Thread instantiates and starts Thread A.
Thread A after X seconds instantiates Thread B.
Thread B is started.
Thread B after X seconds instantiates Thread A.
Thread A is started.
If the call to Thread B is the LAST statement executed in the runnable of Thread A, will Thread A terminate after Thread B is instantiated and started? Or will Thread B be nested in Thread A and therefore create an infinite number of nested threads? What is the default behaviour and how would I accomplish NOT creating an infinite number of threads (I would like every previous thread to end while the child survives).
A Thread.join() would cause the thread to wait until the children thread die, correct?
If this is just bad practice in general, can anyone recommend alternatives that will essentially accomplish the same task? I need one function to, after a few seconds, call another functions which will then run simultaneously with the first function. The first function will then, after completing some commands, die. The second function should then, after a few seconds, call a new instance of the first function. This loop should continue until aborted by the main thread (or until the program exits).
Your question contains the answer: you are thinking of threads as tasks or "functions to run", which they are not. Threads execute tasks, so design your code around the idea of tasks that can create other tasks. Tasks are simply Objects that implement the Runnable interface, nothing more. You can construct these tasks (or runnable objects) with all the data they need, even including references to other (parent) tasks.
Create one CachedThreadPool and whenever a task is ready to be executed, dump the task in the threadpool using the execute method.
One thing you will need to consider is program shutdown: you need to close the ThreadPool in order to close your program gracefully. You can simply call shutdownNow, but you'll probably want to device a technique that gives important tasks a chance to complete and then shutdown. That will take some practice to get it right (shutdownHooks for example are not easy), but from then on you can re-use it whenever you need more than 1 thread.
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.
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.