Java多线程:停止先前的执行并开始新的

huangapple 未分类评论43阅读模式
英文:

Java multithreading: stop previous execution and start new

问题

我有一段代码,应该只能由一个线程在某个时间内执行。如果有新的线程到达此代码块,则应取消先前的执行并开始新的执行。

例子是刷新缓存:

public void refreshCache() {
    //刷新缓存可能需要长达20分钟
}

当然,我可以使用CompletableFuture运行这个代码,将Future存储在AtomicReference中,并在新线程到达时取消它。但是,这是我脑海中唯一的选择。

是否有关于如何处理这种情况的最佳实践?如果我想运行多个服务实例,解决方案会是什么?

英文:

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?

huangapple
  • 本文由 发表于 2020年4月4日 15:56:55
  • 转载请务必保留本文链接:https://java.coder-hub.com/61025247.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定