Java 如何强制ExecutorService.awaitTermination()超时?

Java 如何强制ExecutorService.awaitTermination()超时?,java,junit,concurrency,Java,Junit,Concurrency,被测代码通过ExecutorService.invokeAll()执行一组可调用的对象。然后调用ExecutorService线程池shutdown(),并调用waittermination() ExecutorService threadpool = Executors.newFixedThreadPool(healthChecks.size()); List<Future <HealthStatus> > checkResults = threadpool.invok

被测代码通过
ExecutorService.invokeAll()
执行一组
可调用的
对象。然后调用
ExecutorService
线程池
shutdown()
,并调用
waittermination()

ExecutorService threadpool = Executors.newFixedThreadPool(healthChecks.size());
List<Future <HealthStatus> > checkResults = threadpool.invokeAll(healthChecks);
threadpool.shutdown();

// Now wait for all the threads to finish as part of the shutdown.
if (!threadpool.awaitTermination(STATUS_CHECK_TIMEOUT_SECONDS, TimeUnit.SECONDS))
{
    throw new Exception("Health checks did not all complete in time.");
}
但是,当我运行JUnit测试时,它会立即完成(并且我无法确认超时路径是否在测试代码中)

@Test(预期为java.lang.Exception.class)
public void testStatusTimeout()引发异常{
最终服务员=新服务员();
HealthChecker checker=新超时HealthCheck(
服务器状态检查。状态检查\u超时\u秒*1000*2,
是的,
“testStatusTimeout”,
服务员);
Collection testCollect=newarraylist(1);
testCollect.add(checker);
服务器状态检查检查下测试=
新的ServerStatusCheck(testCollect,新的DefaultDateTimeProvider());
checkUnderTest.Status();
服务员。等待(服务器状态检查。状态检查\u超时\u秒*1000*3);
}
我已经在使用
ConcurrentUnit
Maven软件包(0.4.1),但要么我误解了服务员的工作,要么就是方向不对


如果有必要的话,我将在Eclipse和Java 8下运行JUnit。

发布一些相关代码,以便我们可以检查您的错误。这很公平。我已经添加了代码。有什么想法吗?你使用依赖注入吗?是的,我正在使用依赖注入。发布一些相关的代码,这样我们就可以检查你做错了什么。很公平。我已经添加了代码。有什么想法吗?你用依赖注入吗?是的,我用的是依赖注入。
public static final class TimeoutHealthCheck implements HealthChecker
{
    public final long SleepIntervalMillis;
    String healthName;
    boolean result;
    Waiter waiter;

    public TimeoutHealthCheck(long timeoutInMillis, boolean result, String healthName, Waiter waiter) {
        SleepIntervalMillis = timeoutInMillis;
        this.healthName = healthName;
        this.result = result;
        this.waiter = waiter;
    }
    public HealthStatus call() throws Exception {
        Thread.sleep(SleepIntervalMillis);
        if (waiter != null) {
            waiter.resume();
        }
        return new TestHealthStatus(healthName,result);
    }
}
    @Test(expected = java.lang.Exception.class)
public void testStatusTimeout() throws Exception {

    final Waiter waiter = new Waiter();

    HealthChecker checker = new TimeoutHealthCheck(
            ServerStatusCheck.STATUS_CHECK_TIMEOUT_SECONDS*1000*2,
            true,
            "testStatusTimeout",
            waiter);

    Collection<HealthChecker> testCollect = new ArrayList<HealthChecker>(1);
    testCollect.add(checker);

    ServerStatusCheck checkUnderTest =
            new ServerStatusCheck(testCollect, new DefaultDateTimeProvider());

    checkUnderTest.Status();
    waiter.await(ServerStatusCheck.STATUS_CHECK_TIMEOUT_SECONDS*1000*3);
}