ThreadInterruptedCompletableFuture extends CompletableFuture<R> { @Override public boolean cancel(boolean mayInterruptIfRunning) { cancel = true; if (this.isDone() || this.isCompletedExceptionally()) { LOGGER.warn("Can not be canceled because the caller future isDone or isCompletedExceptionally"); return false; } while (thread == null) { try { LOGGER.warn("Waiting 1s for taskThread to be set..."); Thread.sleep(1000); } catch (InterruptedException e) { LOGGER.warn(e.toString(), e); Thread.currentThread().interrupt(); return false; } } thread.interrupt(); return true; }  void setThread(Thread t); @Override boolean cancel(boolean mayInterruptIfRunning); @Override boolean isCancelled();  }
@Test public void test() throws Exception { ThreadInterruptedCompletableFuture<?> foo = new ThreadInterruptedCompletableFuture<>(); boolean[] result = new boolean[2]; Thread t = new Thread() { @Override public void run() { result[0] = foo.cancel(true); result[1] = Thread.currentThread().isInterrupted(); } }; t.start(); t.interrupt(); t.join(100); assertFalse(result[0]); assertTrue(result[1]); }