0

I have a thread which is looping a queue, reading tasks and delegating them to a CachedThreadPool. This queue is continuously being filled with client-submitted tasks.

I want the reader thread to terminate if the client programs also terminates. At first I thought that setting the reader thread as a daemon would solve the problem. However, there are two problems with this:

  • The reader thread needs to read all the events still left in the queue before it exits.
  • The reader thread has a CachedThreadPool. Since the threads in it are not daemon, the program will no exit. If I set all the threads in the pool as daemon, somehow they do not process all the work (probably because the reader will terminate before processing all the queue).

I also tried to solve this with a shutdown hook, however the hook is never called at the right time (maybe because I'm running the client from a build tools? (Scala's SBT)).

Any hints on getting around this?

halfwarp
  • 1,780
  • 5
  • 24
  • 41

3 Answers3

2

You could use an ExecutorService instead. It manages the queue and the thread(s) and can be shutdown().

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

You can use a 'poison task' to signal reader thread that it should stop its work and shutdown the CachedThreadPool.

Boris Pavlović
  • 63,078
  • 28
  • 122
  • 148
0

When you have a continuous loop such as the one your reader goes round, you should provide some way to notify it to stop. This can be as simple as a boolean on whatever class you implemented the reader in.

public class QueueReader implements Runnable
{
  private boolean runIndicator = false;

  public void run()
  {
    runIndicator = true;
    while (runIndicator)
    {
      //poll the queue with a timeout
      //submit any task from the queue to the cached thread pool
    }

    //shutdown the cached thread pool
  }

  public void stop()
  {
    runIndicator = false;
  }

}

Note that when you call stop() it will still wait for the queue poll to time out and will still submit any task it finds on there.

Qwerky
  • 18,217
  • 6
  • 44
  • 80
  • For completeness, you should probably go ahead and declare the boolean as `volatile` (see http://stackoverflow.com/questions/106591/do-you-ever-use-the-volatile-keyword-in-java) – J. Dimeo Aug 27 '16 at 01:21