Reputation: 1013
I need to write a multi-threaded java application where I will be creating number of threads to handle different types of operation. For example, one thread will monitor state of the application, one thread will manage communication with other nodes in the cluster, one thread will have some application logic and so on.
What is the good way to pass the data and signals between the threads? For example, the application logic thread may need to send a message which it can hand off to the communication thread. Here the data will need to be transferred between the two threads. One way I thought was to use a queue where all the threads wanting to send a message can insert their message. However, it presents few problems:
Moreover, such send method will provide no way for me to tell the calling thread if the sending fails (for example, throwing an exception) because once the message is inserted in the queue, the calling thread thinks it sent its message.
What is the good way to pass signal and data between the threads for such applications?
This might be too fundamental question for software engineers (I come from electronics background). If so, can anyone point me to a good source where I can read about designing multi-threaded or multi-processed applications?
Thanks a lot.
Upvotes: 0
Views: 3937
Reputation: 65793
I posted here on a similar question recently.
You are looking for a BlockingQueue
and as the code there shows, they are easy to work with.
Of your points:
The queue and the method used for insertion will need to be static OR
No - as you can see in the sample, if you build the queue and pass it to both objects that wish to communicate (or keep them all in a Map
like I did in that answer) they can work quite happily together.
Each thread that wishes to send a message has to have the object of the communication thread
No - just the queue.
Moreover, such send method will provide no way for me to tell the calling thread if the sending fails ...
Just because you have put the message in the queue doesn't mean you can't keep hold of it. You could wait for it to be changed by the other thread and respond to that or you could have two queues, one for the message and one for the response or put a semaphore in the massage that gets tripped when the message is actioned. It's just like wiring up a circuit.
Being from an electronics background doesn't mean you have to apologise - someone has to keep the lights on. {grin}
Upvotes: 1