Closing external process in CompletableFuture chain
<p>I'm looking for better way to "close" some resource, here destroy external <code>Process</code>, in <code>CompletableFuture</code> chain. Right now my code looks roughly like this:</p>

<pre><code>public CompletableFuture&lt;ExecutionContext&gt; createFuture()
{
    final Process[] processHolder = new Process[1];
    return CompletableFuture.supplyAsync(
            () -&gt; {
                try {
                    processHolder[0] = new ProcessBuilder(COMMAND)
                            .redirectErrorStream(true)
                            .start();
                } catch (IOException e) {
                    throw new UncheckedIOException(e);
                }
                return PARSER.parse(processHolder[0].getInputStream());
            }, SCHEDULER)
            .applyToEither(createTimeoutFuture(DURATION), Function.identity())
            .exceptionally(throwable -&gt; {
                processHolder[0].destroyForcibly();
                if (throwable instanceof TimeoutException) {
                    throw new DatasourceTimeoutException(throwable);
                }
                Throwables.propagateIfInstanceOf(throwable, DatasourceException.class);
                throw new DatasourceException(throwable);
            });
}
</code></pre>

<p>The problem I see is a "hacky" one-element array which holds reference to the process, so that it can be closed in case of error. Is there some <code>CompletableFuture</code> API which allows to pass some "context" to <code>exceptionally</code> (or some other method to achieve that)? </p>

<p>I was considering custom <code>CompletionStage</code> implementation, but it looks like a big task to get rid of "holder" variable.</p>