Created
August 15, 2012 00:36
-
-
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?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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! | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
StackOverflow question: http://stackoverflow.com/q/11962809/110856