Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 :)

like image 804
Dori Avatar asked Aug 09 '11 11:08

Dori


People also ask

How do you make a thread pause indefinitely?

You can specify Timeout. Infinite for the millisecondsTimeout parameter to suspend the thread indefinitely.

What are some ways to prevent threads from running forever?

The only way to stop an arbitrary thread is by interrupting it. Keep a reference to it then call the interrupt method.

How do I make thread wait?

The wait() Method Simply put, calling wait() forces the current thread to wait until some other thread invokes notify() or notifyAll() on the same object. For this, the current thread must own the object's monitor.

Can you pause a thread?

Thread. sleep() method can be used to pause the execution of current thread for specified time in milliseconds.


2 Answers

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).

like image 133
Tomasz Nurkiewicz Avatar answered Sep 20 '22 16:09

Tomasz Nurkiewicz


You could use the java.util.concurrent library, if the data structures there meet your needs. Something like BlockingQueue might work for you.

like image 39
Sean Reilly Avatar answered Sep 19 '22 16:09

Sean Reilly