维护单个执行程序服务并适当关闭它

Maintaining a single executor service and shutting it down appropriately

我的应用程序需要异步完成某项工作,所以我求助于执行程序框架。如果某个外部接口出现故障(供应商可以备份一段时间,比如 30 分钟),这项工作(Runnable)预计会 运行。

考虑到这个问题,我相信我应该维护一个固定编号的预定执行程序服务。当我上面所说的接口短暂关闭时执行这些作业的核心线程的数量(作为 class 中的 static 变量,我需要线程池)。我也不认为我应该为每个需要创建一个执行程序来处理这样的工作(单个调度线程池执行程序),并在工作 运行 后关闭,因为那样会破坏我的目的,不会它?因为这可能意味着在备份时间内为每个作业保留一个线程,这对我来说听起来很可怕。

但是,如果我要维护这样一个执行器服务,我什么时候关闭执行器?我知道执行程序一旦关闭就不能再使用,而不关闭执行程序并保持线程处于活动状态可以防止 JVM 关闭。我该怎么做?

我最后的陈述是基于 Effective Java 2nd edition:

And here is how to tell the executor to terminate gracefully (if you fail to do this, it is likely that your VM will not exit):

executor.shutdown();

This job (a Runnable) is expected to be run should a certain external interface be down (the vendor could be backed up for a while, say, 30 mins).

以上是您的要求。现在解决方案完全取决于如何处理上述情况。

  • 触发器或事件监听器: 如果你有一些触发器或事件监听器,当发现某个外部接口宕机时可以调用,那么在触发的代码或事件侦听器中,您可以创建一个 ExecutorService,执行所有任务(您可以选择固定线程池或池线程池),然后在完成所有任务后,您可以关闭 ExecutorService
    在这种情况下,最好创建一个 ExecutorService,执行任务并关闭它。不需要 long 运行 ExecutorService.

  • 跟踪或定期检查:如果你必须定期跟踪或检查某个外部接口是否关闭,那么我认为你可以有一个ScheduledThreadPoolExecutor 实现在固定时间间隔后检查某个外部接口是否关闭,如果关闭则执行所有任务。在这种情况下,您不会关闭您的 ExecutorService,它将始终是 运行。

P.S.: Trigger 和 Track 是我自己的约定,我切线地把它当作一个词来使用,所以请用专业术语来推断。

I understand that an executor once shut down can't be reused, while not shutting down the executor and keeping threads active could prevent the JVM from shutting down.

是的,执行器一旦关闭就不能再使用。
不,运行 ExecutorService 不会阻止 JVM 关闭,但是一旦 JVM 关闭,ExecutorService 实例及其线程池将被停止并销毁。