在Java / Kotlin的ThreadPool中取消被取代的任务

我试图找出如何取消一个任务在一个ThreadPool如果一个新的任务来取代它。 我有一些类似这样的:

 class RenderableThing { private val lock = ReentrantLock() fun lock(interrupt: Boolean) { if (lock.isLocked && interrupt) { // How do I interrupt the thread that has the lock? } lock.lock() } fun unlock() = lock.unlock() fun cache() = Cached() inner class Cached() } class BackgroundStuff(threads: Int) { val pool = Executors.newFixedThreadPool(threads)!! fun doBackgroundStuff(thing: RenderableThing): Future<Stuff> { val cache = thing.cache() return pool.submit { try { thing.lock() // Do long running I/O task on cache } finally { thing.unlock() } } } } 

但是,如果相同的RenderableThing被提交给doBackgroundStuff (已经做了更改并且需要保存到磁盘),我希望能够取消之前提交的Future (因为它现在已经过期,被覆盖,没有理由等待它完成了)。 问题是,锁定发生在未来还不存在的内部。

我知道你永远不应该强制杀死一个锁定的线程(我什至不知道如何,因为它是一个ReentrantLock ),那么这是做什么正确的方法?

编辑 :我的问题是不同的,因为我没有进入将来取消它(锁没有放置到位,直到ThreadPool拿起,到这一点的thing可能已提交多次,我不知道哪一个会拥有锁)。 如果我这样做,将是一块蛋糕(处理中断的代码已经到位)。 我应该如何改变我的代码来获得对拥有锁的未来(甚至线程)的引用?

我只是想知道这段代码是否工作:

 //... fun doBackgroundStuff(thing: RenderableThing): Future<Stuff> { LLget(thing)?.cancel(true) val cache = thing.cache() val f = pool.submit { try { thing.lock() // Do long running I/O task on cache } finally { thing.unlock() } } LLput(thing, f) return f } //... object L { val L: IdentityHashMap<RenderableThing, Future<Stuff>> ? = IdentityHashMap<>() }