英文:
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?
专注分享java语言的经验与见解,让所有开发者获益!
评论