My situation is that I have two threads. The 1st thread produces a number of objects which the 2nd thread does not have access to until all of them are created. After that the 2nd thread reads fields in those objects but does so concurrently with the 1st. At this point no thread is changing the values of the fields of the objects.
The objects are not synchronized. Should I synchronize them or not?
My situation is that I have two threads. The 1st thread produces a number
Share
What I would recommend is to use an
AtomicReference<Collection<SomeObject>>. The first thread would produce the collection of objects and do areference.put(collection). The 2nd thread would see the objects (reference.get()) after they have been set on theAtomicReferenceonly. Here are the javadocs forAtomicReference. You could also set your objects as an array or any type of collection such asList.If is important to realize that after your set the collection (or array) on the
AtomicReferenceyou cannot make any changes to the collection. You can’t add additional items, clear it, etc.. If you want true concurrent access to a collection of objects then you should look intoConcurrentHashMapand friends.If the objects are not going to be mutated at all after they are put in your collection then you do not need to make them synchronized.