Spring 任务执行器实现

Spring TaskExecutor Implementation

我正在处理的应用程序接收来自外部系统的通知,我想按顺序处理这些通知,因为我遇到了一些死锁。

我正在使用 Spring 的 TaskExecutor,它相当于 JDK 1.5 的执行器。

我是通过以下方式实现的:

我有一个 java 接口包含 1 个方法:

    public interface AsynchronousService {
    void executeAsynchronously(Runnable task);
}

以及相应的实现:

    public class AsynchronousServiceImpl implements AsynchronousService {

    private TaskExecutor taskExecutor;

    @Override
    public void executeAsynchronously(Runnable task) {
        taskExecutor.execute(task);
    }

    @Required
    public void setTaskExecutor(TaskExecutor taskExecutor) {
        this.taskExecutor = taskExecutor;
    }
}

这里是TaskExecutor的配置。我不确定这个配置。因为,我希望通知按顺序执行,所以我将 corePoolSize 和 maxPoolSize 都设置为 1。这意味着只会在线程池中创建 1 个线程,并从队列中按顺序检索通知。我还为 "WaitForTasksToCompleteOnShutdown" 设置了 "false" 以便在每个任务执行后不关闭,而是在 spring 上下文被破坏时关闭。我的假设大体上正确吗?

<bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
    <property name="corePoolSize" value="1"/>
    <property name="maxPoolSize" value="1"/>
    <property name="WaitForTasksToCompleteOnShutdown" value="false"/>
</bean>

这里我执行代码:

 asynchronousService.executeAsynchronously(new Runnable() {
     @Override
     public void run() {
         someMethod.processNotification(notification)
      }
   });

你觉得我的实现怎么样?我错过了什么? 我不确定 if/where 我需要实施一些错误处理吗?

编辑: 是否有可能调整 spring 中任务执行器的实现以使用自定义队列?或者确定队列中任务的优先级有多难?我查看了一些实现,但其中大多数实现了 sratch 中的执行程序服务,而没有使用 Spring.

The application I am working on receives notifications from external systems, which I want to process sequentially, since I am experiencing some deadlocks.

如果你顺序处理,你就不需要线程池了。

Since, I want the notifications to execute sequentially, I set 1 for both, corePoolSize and maxPoolSize

这将创建一个大小为 1 的固定池。只有一个线程,因此它将按顺序执行

I also set "false" for "WaitForTasksToCompleteOnShutdown" in order not to shutdown after each task is executed, but rather when the spring context is destroyed

这是错误的。此标志告诉池在关闭时等待任务完成(例如,如果您调用 pool.shutdownNow(),池将等待任何正在执行的线程)

总结一下:如果你想在没有并发的情况下逐个执行,请不要使用线程池