Java multithreading: stop previous execution and start new

Viewed 66

I have a block of code, which should be executed only by one thread in time. If new thread arrives at this block - it should cancel previous execution and start a new one.

The example is a refreshing cache:

public void refreshCache() {
    //refresh cache can take up to 20 minutes
}

Of course, I can run this with CompletableFuture, store Future in an AtomicReference and cancel it when new thread arrives. But, that's the only option I have in mind.

Are there any best practices on how to handle such cases? What will be the solution if I want to run multiple instances of service?

0 Answers
Related