I have a Java application which has worker threads to process jobs. A worker produces a result object, say something like:
class WorkerResult{
private final Set<ResultItems> items;
public Worker(Set<ResultItems> pItems){
items = pItems;
}
}
When the worker finishes, it does this operation:
...
final Set<ResultItems> items = new SomeNonThreadSafeSetImplSet<ResultItems>();
for(Item producedItem : ...){
items.add(item);
}
passToGatherThread(items);
The items
set is kind of a "unit-of-work" here. The passToGatherThread
method passes the items
set to a gather thread, of which only one exists at runtime.
Synchronization is not needed here, since race conditions cannot occur because only one thread (Gather-thread) reads the items
set. AFAICS, the Gather-thread may not see all items because the set is not thread-safe, right?
Assume I cannot make passToGatherThread
synchronized, say because it is a 3rd party library. What I basically fear is that the gather thread does not see all items because of caching, VM optimizations, etc. So here comes the question: How to pass the items set in a thread-safe manner, such that the Gather thread "sees" the proper set of items?