Are array elements correctly published between workers?
Suppose I have a big array (of any atomic data type, so not long
or double
),
future.get()
). The worker doesn't return anything. It just fills my array.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.
ExecutorService is a JDK API that simplifies running tasks in asynchronous mode. Generally speaking, ExecutorService automatically provides a pool of threads and an API for assigning tasks to it.
ExecutorService does not mandate or otherwise guarantee that all implementations are thread-safe, and it cannot as it is an interface. These types of contracts are outside of the scope of a Java interface. However, ThreadPoolExecutor both is and is clearly documented as being thread-safe.
Executors provide factory methods that are being used to create ThreadPools of worker threads. Thread pools overcome this issue by keeping the threads alive and reusing the threads. Any excess tasks flowing in that the threads in the pool can handle are held in a Queue.
We'll first use the shutdown method of ExecutorService to terminate a thread pool gracefully. When we invoke shutDown, the thread pool stops accepting new tasks. Then, it waits for already submitted tasks to complete even if they didn't start yet.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With