I have a Java Thread which handles outgoing communication with a Socket. I only want the thread to run while there is pending output ready to be sent. Say I have a Stack<String> that holds the data waiting to be sent, I would like the comms thread to wake up when something is added to the stack and go to sleep when the stack is empty. Whats the best approach for this?
Options i see are;
- Using
wait()/notify()– now seems to be the old way of acheiving this behaviour - Having the thread check every x milliseconds if there is anything to be sent
- Constructing a new
Threadeach time (expensive) - Having the thread run constantly (expensive)
- Implementing some thread pool or executor solution
Any advice would be great 🙂
BlockingQueueis exactly what you are looking for. Your communication thread blocks ontake()and is woken up immediately when some other thread doesadd/put.This approach has several advantages: you can have multiple threads (consumers) sharing the same queue to increase throughput and several threads (producers) generating messages (message passing).