Search code examples
javaconcurrencyexecutorservicehappens-before

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),

  • 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.


Solution

  • 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.