Skip to content

Instantly share code, notes, and snippets.

@cb372
Created August 15, 2012 00:36
Show Gist options
  • Save cb372/3354249 to your computer and use it in GitHub Desktop.
Save cb372/3354249 to your computer and use it in GitHub Desktop.
Can I use Guava's AbstractExecutionThreadService for services that need to be interrupted?
package chris;
import com.google.common.util.concurrent.AbstractExecutionThreadService;
import com.google.common.util.concurrent.Service;
import org.junit.Test;
import java.util.concurrent.*;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
/**
* Created: 12/08/15 9:16
*
* @author chris
*/
public class GuavaServiceTest {
@Test
public void canStopServiceUsingInterruption()
throws ExecutionException, TimeoutException, InterruptedException {
Service service = new MyGuavaService();
assertThat(
service.startAndWait(),
is(Service.State.RUNNING));
assertThat(
service.stop().get(1, TimeUnit.SECONDS),
is(Service.State.TERMINATED)); // FAIL: TimeoutException
}
static class MyGuavaService extends AbstractExecutionThreadService {
BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(10);
@Override
protected void run() throws Exception {
while (isRunning() && !Thread.currentThread().isInterrupted()) {
int next = queue.take();
System.out.println("Received " + next + ". Processing...");
}
}
@Override
protected void triggerShutdown() {
// Need to interrupt the executor thread here!
}
}
}
@cb372
Copy link
Author

cb372 commented Aug 15, 2012

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment