Concurrent array access by executor service

694 Views Asked by At

Are array elements correctly published between workers?

Suppose I have a big array (of any atomic data type, so not long or double),

  • 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 (e.g. with 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. I perform simple arithmetic on each element.

2

There are 2 best solutions below

1
On BEST ANSWER

From package java.util.concurrent JavaDoc:

The methods of all classes in java.util.concurrent and its subpackages extend these guarantees to higher-level synchronization. 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.

Actions in a thread prior to the submission of a Runnable to an Executor happen-before its execution begins. Similarly for Callables submitted to an ExecutorService.

According to that it seems pretty safe to access an array from the second worker in your scenario.

3
On

The elements of the array aren't volatile, so they might be cached per-thread by the 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