Something like that? The most interesting part is StoppableWrapper#stop() , because graceful undoing is a difficult thing, and there is no general approach for all cases. Once you need to clean the file system, at another time, close the network connection, etc. In your example, you just call interrupt() , so I accepted runThird() differences that break, and will take care to clean things up behind me.
class Sample { final ExecutorService tasksExecutor = Executors.newCachedThreadPool(); class StoppableWrapper implements Runnable { private final Runnable task; private final CountDownLatch executed; StoppableWrapper(Runnable task, CountDownLatch executed) { this.task = task; this.executed = executed; } void stop() {
source share