Search code examples
javaconcurrencyrunnableexecutorservicejava.util.concurrent

java.util.concurrent: Transition from Runnable to Executor interface


I am writing a JUnit test case for a DSL, and I need to ensure that the method under test does never end (as in this question).

The provided solution is fine, but I would like to use the "new" Executor interface (Java 5.0 onwards):

@Test
public void methodDoesNotReturnFor5Seconds() throws Exception {
  Thread t = new Thread(new Runnable() {
    public void run() {
      methodUnderTest();
    }
  });
  t.start();
  t.join(5000);
  assertTrue(t.isAlive());
  // possibly do something to shut down methodUnderTest
}

How can I translate the above code from the "old" Thread/Runnable interface to the "new" ExecutorService/Executor interface?


Solution

  • Future<?> future = Executors.newSingleThreadExecutor().submit(new Runnable() {
        public void run() {
            methodUnderTest();
        } 
    });
    try {
        future.get(5, TimeUnit.SECONDS);
        fail("The task has completed before 5 seconds");
    }
    catch (TimeoutException e) {
        // expected
    }