[Java] Always handle future returned by ExecutorService#submit

When using ExecutorService#submit a future is returned. This future contains all exceptions that were thrown during execution. If this future i not handled exceptions get lost without any notice. Ususally exceptions that are not handled are bugs in the system. At least they should be logged for later analysis of the problem. If they are not logged and not handled the discovery and the analyisis of bugs will take much longer. If I dont want to handle exceptions explicitely ExecutorService#execute can be used that will hand exceptions to some default exception handler that at least loggs the error.

Hence the rule should be either handle the future or use the execute method instead of submit.

Non compliant code:

_executor.submit(() ->
        {
            throw new IllegalStateException("I dont want to work");
        });

Compliant code:

         // when submit is used the future has to be handled
         Future<Object> future = _executor.submit(() ->
        {
            throw new IllegalStateException("I dont want to work");
        });

        try
        {
            future.get();
        }
        catch (InterruptedException e)
        {
            LOG.warn("Execution was interrupted.", e);
            Thread.currentThread().interrupt();
        }
        catch (ExecutionException e)
        {
            LOG.warn("An error occured during execution. Handling it.", e);
            // handle exception
        }

or:

        // fire and forget -> no future has to be handled, exceptions are logged
        _executor.execute(() -> LOG.info("I am working"));
  • type : Bug, Code Smell