Reputation: 18403
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;
wait()/notify()
- now seems to be the old way of acheiving this behaviourThread
each time (expensive)Any advice would be great :)
Upvotes: 10
Views: 2744
Reputation: 340693
BlockingQueue
is exactly what you are looking for. Your communication thread blocks on take()
and is woken up immediately when some other thread does add
/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).
Upvotes: 7
Reputation: 21836
You could use the java.util.concurrent library, if the data structures there meet your needs. Something like BlockingQueue might work for you.
Upvotes: 4