Can I use Guava's AbstractExecutionThreadService for services that need to be interrupted?

Viewed 2860

I have a service that I would like to implement as a Google Guava Service.

The service basically runs a while (true) loop that processes events as they arrive on a BlockingQueue. Simplified sample code is available here:

https://gist.github.com/3354249

The problem is that the code blocks on BlockingQueue#take(), so the only way to stop the service is to interrupt its thread. Is this possible using Guava's AbstractExecutionThreadService?

Of course, in this case I could replace queue.take() with a polling loop using queue.poll(1, TimeUnit.SECONDS), thus removing the need for thread interruption. However:

  • I would like to avoid doing this, for both performance and code readability reasons

  • There are other cases where it is impossible to avoid thread interruption, e.g. if the service is blocked while reading bytes from an InputStream.

2 Answers
Related