简体   繁体   English

执行程序服务并发访问数组

[英]Concurrent array access by executor service

Are array elements correctly published between workers? 工人之间是否正确发布了数组元素?

Suppose I have a big array (of any atomic data type, so not long or double ), 假设我有一个大数组(任何原子数据类型,所以不要longdouble ),

  • I create a worker that fills the array that I pass to it's contructor, 我创建了一个工作人员,该工作人员填充了传递给它的构造函数的数组,
  • I submit the worker to an executor, and wait until it's complete ( eg with future.get() ). 我将工人提交给执行者,并等待其完成( 例如,使用future.get() )。 The worker doesn't return anything. 工人什么也没退。 It just fills my array. 它只是填充我的数组。
  • Then, I immediately create and submit another worker with the same array in it's contructor. 然后,我立即在构造器中创建并提交另一个具有相同数组的工作器。 Does it see the latest values? 是否看到最新值?

In other words, it it guaranteed that the last write of the previous worker happens-before the first read of the next worker? 换句话说,它保证了上一个工作程序的最后写入发生在下一个工作程序的第一次读取之前?

Should I instead (or for best practice or something) let the first worker return the array, even though the reference is the same as the one I have already have? 即使引用与我已有的引用相同,我还是应该(或者出于最佳实践之类的考虑)让第一个工作者返回该数组吗?

[Edit] Some background: I use either byte arrays or short arrays, which represent images and use up to 500,000,000 elements each. [编辑]背景:我使用byte数组或short数组来表示图像,每个数组最多使用500,000,000个元素。 I perform simple arithmetic on each element. 我对每个元素执行简单的算术运算。

From package java.util.concurrent JavaDoc : 包java.util.concurrent JavaDoc中

The methods of all classes in java.util.concurrent and its subpackages extend these guarantees to higher-level synchronization. java.util.concurrent中所有类的方法及其子包将这些保证扩展到更高级别的同步。 In particular: 特别是:

Actions taken by the asynchronous computation represented by a Future happen-before actions subsequent to the retrieval of the result via Future.get() in another thread. 由Future表示的异步计算采取的操作发生在通过另一个线程中的Future.get()检索结果之后的操作之前。

Actions in a thread prior to the submission of a Runnable to an Executor happen-before its execution begins. 在将Runnable提交给执行者之前,线程中的操作会在执行开始之前发生。 Similarly for Callables submitted to an ExecutorService. 对于提交给ExecutorService的Callables也是类似的。

According to that it seems pretty safe to access an array from the second worker in your scenario. 因此,从您的方案中的第二个工作线程访问阵列似乎非常安全。

The elements of the array aren't volatile , so they might be cached per-thread by the CPU. 数组的元素不是volatile ,因此它们可能会被CPU按线程缓存。 It's therefore possible for the first worker to initialize some array element, but for the second worker to not see it due to caching. 因此,第一个工作程序可能会初始化某个数组元素,而第二个工作程序则可能由于缓存而看不到它。

To make sure that the array elements are themselves atomic, you can use an AtomicReferenceArray 为了确保数组元素本身是原子的,可以使用AtomicReferenceArray

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM