gpt4 book ai didi

multithreading - 为什么使 ItemReader 线程安全会导致我们失去可重新启动性?

转载 作者:行者123 更新时间:2023-12-04 06:50:05 24 4
gpt4 key购买 nike

我有一个从数据库读取的多线程批处理作业,我担心不同的线程会重新读取记录,因为 ItemReader 在 Spring 批处理中不是线程安全的。我经历了SpringBatch FAQ部分指出

You can synchronize the read() method (e.g. by wrapping it in a delegator that does the synchronization). Remember that you will lose restartability, so best practice is to mark the step as not restartable and to be safe (and efficient) you can also set saveState=false on the reader.



我想知道为什么在这种情况下我会失去可重新启动性?可重启性与同步我的读取操作有什么关系?它总是可以再试一次,对吧?
另外,这段代码是否足以同步阅读器?
  public SynchronizedItemReader<T> implements ItemReader<T> {
private final ItemReader<T> delegate;
public SynchronizedItemReader(ItemReader<T> delegate) {
this.delegate = delegate;
}
public synchronized T read () {
return delegate.read();
}
}

最佳答案

当使用带有多线程的 ItemReader 时,缺乏可重新启动性与读取本身无关。这是关于保存更新方法中发生的阅读器状态。问题是调用 read() - 提供数据的方法和 update() - 保持状态的方法之间需要协调。当您使用多个线程时,读取器的内部状态(以及因此 update() 调用)可能会也可能不会反射(reflect)已完成的工作。以 FlatFileItemReader 为例,它使用 5 的 block 大小并在多个线程上运行。您可能让线程 1 读取了 5 个项目(更新时间),但线程 2 可能已经读取了另外 3 个项目。这意味着对更新的调用将保存已读取的 8 个项目。如果线程 2 上的 block 失败,则状态将不正确,并且重新启动将丢失已读取的三个项目。

这并不是说不可能编写线程安全的 ItemReader。但是,正如您上面的示例所示,如果委托(delegate)是有状态的 ItemReader (也实现了 ItemStream),则状态将不会通过调用 update 正确持久化(实际上,您上面的示例甚至没有采用分阶段阅读器的 ItemStream 方面考虑)。

关于multithreading - <Spring Batch> 为什么使 ItemReader 线程安全会导致我们失去可重新启动性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19971973/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com