Dori
Dori

Reputation: 18403

Getting a Thread to wait indefinitely

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;

  1. Using wait()/notify() - now seems to be the old way of acheiving this behaviour
  2. Having the thread check every x milliseconds if there is anything to be sent
  3. Constructing a new Thread each time (expensive)
  4. Having the thread run constantly (expensive)
  5. Implementing some thread pool or executor solution

Any advice would be great :)

Upvotes: 10

Views: 2744

Answers (2)

Tomasz Nurkiewicz
Tomasz Nurkiewicz

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

Sean Reilly
Sean Reilly

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

Related Questions