Say I have a data object:
class ValueRef { double value; }
Where each data object is stored in the main collection:
Collection<ValueRef> masterList = ...;
I also have a set of tasks, where each task has a local set of data objects (where each data object also appears in masterList
):
class Job implements Runnable { Collection<ValueRef> neededValues = ...; void run() { double sum = 0; for (ValueRef x: neededValues) sum += x; System.out.println(sum); } }
Use case:
for (ValueRef x: masterList) { x.value = Math.random(); }
Define a job queue using some jobs.
Thread Pool Awakening
Wait until each assignment is rated.
Note. During performance evaluation, all values ββare constant. However, threads may have evaluated jobs in the past and stored cached values.
Question: What is the minimum amount of synchronization needed to ensure that each thread sees the latest values?
I understand synchronization from the point of view of the monitor / lock, I do not understand synchronization from the point of view of the cache / flash (that is, which is guaranteed by the memory model when the synchronized block enters / exits).
It seems to me that I need to synchronize once in a thread that updates the values ββto commit new values ββin the main memory and once per worker thread to clear the cache so that new values ββare read. But I'm not sure how best to do this.
My approach: create a global monitor: static Object guard = new Object();
Then sync with guard
when updating the main list. Then, finally, before starting the thread pool, once for each thread in the pool, synchronize on guard
in an empty block.
Does this really cause a full stream of any value read by this stream? Or just the values ββaffected inside the synchronization block? In this case, instead of an empty block, maybe I should read each value once in a loop?
Thank you for your time.
Edit: I think my question comes down to the fact that, as soon as I exit the synchronized block, every first time it reads (after this point) the transition to the main memory? No matter what I synced?