Bat0u89
Bat0u89

Reputation: 438

Should I access (not change) an object from multiple threads?

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?

Upvotes: 0

Views: 114

Answers (2)

Gray
Gray

Reputation: 116878

What I would recommend is to use an AtomicReference<Collection<SomeObject>>. The first thread would produce the collection of objects and do a reference.put(collection). The 2nd thread would see the objects (reference.get()) after they have been set on the AtomicReference only. Here are the javadocs for AtomicReference. You could also set your objects as an array or any type of collection such as List.

If is important to realize that after your set the collection (or array) on the AtomicReference you 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 into ConcurrentHashMap and friends.

Should I synchronize them or not?

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.

Upvotes: 4

Chris Thompson
Chris Thompson

Reputation: 35598

There's nothing wrong with reading data from multiple threads at the same time. Issues arise when you attempt to modify that data. So long as the objects are fully initialized and the values are such that the second thread receives the actual value (no issues with caching etc), there no problem with reading data from multiple threads concurrently.

Upvotes: 1

Related Questions