Skip to content

Instantly share code, notes, and snippets.

@eugeniyk
Created September 13, 2023 21:19
Show Gist options
  • Save eugeniyk/5594c8ef89134eb2c76c0bdb948893c0 to your computer and use it in GitHub Desktop.
Save eugeniyk/5594c8ef89134eb2c76c0bdb948893c0 to your computer and use it in GitHub Desktop.
Demonstration of the case where inner future does receive an interruption signal - outerExecutorService lambda explicitly catch it
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicReference;
public class InnerInterruptionCorrectExample {
public static void main(String[] args) throws InterruptedException {
// Create a ExecutorService for managing threads
ExecutorService outerExecutorService = Executors.newSingleThreadExecutor();
ExecutorService innerExecutorService = Executors.newSingleThreadExecutor();
AtomicReference<Future<String>> innerFuture = new AtomicReference<>();
Future<String> outerFuture = outerExecutorService.submit(() -> {
try {
// Create a Future to hold the result of a task
innerFuture.set(innerExecutorService.submit(() -> {
try {
// Simulate some time-consuming operation
Thread.sleep(5000); // Sleep for 5 seconds
System.out.println("Task completed successfully!");
return "Done";
} catch (InterruptedException e) {
// Handle interruption
System.out.println("Task was interrupted!");
return "Error";
}
}));
return innerFuture.get().get();
} catch (InterruptedException e) {
Future<String> inner = innerFuture.get();
if (inner != null) {
inner.cancel(true);
}
return "Outer Error";
}
});
Thread.sleep(1000);
outerFuture.cancel(true);
Thread.sleep(1000);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment