【问题标题】:Spring Batch Tasklet with Task-Executor带有任务执行器的 Spring Batch Tasklet
【发布时间】:2019-10-05 04:54:38
【问题描述】:

我遇到了一个关于带有任务执行器的春季批处理小任务步骤的奇怪问题。配置正常简单,就是一个tasklet(不面向chunk)如下:

<batch:job id="MyJob" restartable="false">
        <batch:step id="MyJob.Step1">
            <batch:tasklet ref="someBean" task-executor="simpleAsyncTaskExecutor" throttle-limit="1"/>
        </batch:step>
</batch:job>

someBean 是一个实例实现的Tasklet 接口。奇怪的是,当我启动作业时,execute 方法调用了两次:

@Override
    public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {

    // some logic and no exception

    return RepeatStatus.FINISHED;
}

实际上创建了两个线程并执行了两次逻辑。如果我将任务执行器更改为正常 task-executor="syncTaskExecutor" (org.springframework.core.task.SyncTaskExecutor) ,只创建了一个线程并调用了一次execute()。

有没有人遇到过这种情况并可以给出一些想法?真不知道“谁”和“什么时候”创建了两个线程?谢谢

【问题讨论】:

    标签: spring multithreading spring-batch


    【解决方案1】:

    当你指定一个异步task-executor时,你的tasklet会被多个线程并发执行。可以使用throttle-limit 设置限制,默认为 4。在您的情况下,两个线程将执行 tasklet。

    另一方面,SyncTaskExecutor 将在调用线程中运行 tasklet,这意味着只运行一次,因为没有创建其他线程。

    【讨论】:

    • 谢谢马哈茂德。所以如果我将油门限制设置为 1 它将运行两次而不是一次?另外我注意到我在 SimpleAsyncTaskExecutor 中覆盖了 doExecute(Runnable task) 方法,如果执行 task.run() 将只运行一个线程,但如果 Thread thread = new Thread(task);线程.start();将使两个线程运行并执行两次任务。但是我需要创建一个新线程来在某个阶段停止它,一个解决方法是在 thread.start(); 之后我使用 countDownLauch.await();然后只有一个线程运行,有点奇怪,但它对我有用。谢谢
    猜你喜欢
    • 2023-02-07
    • 2016-02-03
    • 2018-09-19
    • 1970-01-01
    • 2022-01-13
    • 2019-10-24
    • 1970-01-01
    • 2020-02-19
    • 1970-01-01
    相关资源
    最近更新 更多