Skip to content

Instantly share code, notes, and snippets.

@eugeniyk
Created September 13, 2023 21:14
Show Gist options
  • Save eugeniyk/4ac78fc66ec432a33f6895ea79f0fd80 to your computer and use it in GitHub Desktop.
Save eugeniyk/4ac78fc66ec432a33f6895ea79f0fd80 to your computer and use it in GitHub Desktop.
Demonstration of the case where inner future doesn't receive interruption signal - it has to be explicitly set by outerExecutorService lambda
package com.glovoapp.jvmkit.context.demo.app.models;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicReference;
public class InnerInterruptionTest {
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(() -> {
// 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();
});
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