如何优雅地停止Java ExecutorService的有问题的线程?

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

How to gracefully stop a Java ExecutorService’s troubled thread?

问题

我正在将可调用对象提交给executorService(fixedThreadPool)。

并在可调用对象中存储线程的引用。

现在问题在于,我在这些线程中调用了其他人的回调方法(假设我们有一个带有一个接口的JAR包,该接口的实现是目标产品完成的),因此基本上我无法控制其他产品在该线程中正在做什么。
因此,有时由于某些套接字连接问题,该线程会无限期地被阻塞,现在问题是我不想等待该线程结束,我想优雅地终止该线程。

我尝试过使用thread.interrupt(),但它只能中断被阻塞、等待和休眠的线程。无法通过这种方式中断可运行或正在工作的线程。
(注意:我可以使用thread.stop()强制终止此线程,但由于不推荐那样做,我不想这样做,我正在寻找一个优雅的解决方案)

现在假设我不能因为某些限制而无法终止该线程,但问题在于如果我在我的future任务上调用future.cancel(true),我不能从执行器池中释放此线程,基本上我不能再重用该执行器任务(在这里,我基本上有一个静态引用,该引用在循环中被重用),我甚至尝试过使用executorService.shutdown和shutdownNow,但没有任何方法能够从executor service中释放该线程。

所以,是否有任何方法可以优雅地终止此线程并将其从executor service中释放出来。

英文:

I am submitting callables to executorService (fixedThreadPool).

and storing the reference of the thread in callable object.

now the problem here is, in these threads, I am calling someone else's callback method(consider we have a jar with one interface and that interface's implementation is done by the targeted product), so basically I have no control on what other product is doing in that thread.
so sometimes what happens is due to some socket connection issues this thread gets stuck for an indefinite time and now, here is the issue I do not want to wait for that thread to end I want to kill that thread gracefully.

I tried with thread.interrupt() but it is only able to interrupt blocked, waiting and sleeping threads. The runnable or working thread can not be interrupted by this.
(Note: I am able to kill this thread forcefully using thread.stop() but as that is not recommended I do not want to do that, I am searching for a graceful solution)

now let us say it is ok that I am not able to kill this thread due to some limitations but the problem here is if I call future.cancel(true) on my future task I am not able to free this thread from my executor pool, basically I can not reuse that executor task anymore(here basically I have a static reference of executor service which has been reused in the loop), I have even tried using executorService.shutdown and shutdownNow nothing was able to free that thread from executor service.

so is there any way to kill this thread gracefully and free it from executor service.

huangapple
  • 本文由 发表于 2020年4月10日 02:40:00
  • 转载请务必保留本文链接:https://java.coder-hub.com/61128021.html
匿名

发表评论

匿名网友

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

确定