Search code examples
javafuturejava.util.concurrentconcurrency

Is calling Future#get(time, timeunit) directly (without checking isDone()) a bad practice?


This code runs some really cheap (in terms of time) method in a separate thread, so it's guaranteed with a 99.9999% certainty that the outer method will return successfully. If time it takes to finish the job is more than 5 seconds, I wish to terminate the execution anyway. So, does the code below need some wrapping in if (future.isDone()) ... etc or under my circumstances I can leave it as is?

final Future<SubE> futureEffect = threadPool.submit(effectCallable(lhs, rhs));
try {
    return futureEffect.get(5, TimeUnit.SECONDS);
} catch (InterruptedException | TimeoutException e) {
    throw new eRuleLoadingFailed(e.getMessage());
} catch (ExecutionException e) {
    if (e.getCause() instanceof eAccessDenied) {
        throw (eAccessDenied)e.getCause();
    } else {
        throw new eRuleLoadingFailed(e.getMessage());
    }
}

Solution

  • You will not need isDone here. In fact it would destry your code. In the rare case that the executed code finishes a microsecond AFTER the main thread gets to the if, isDone would return false and the get would not be executed at all. I think this is not what you want. You want to execute get in all cases.