blue-sky
blue-sky

Reputation: 53806

If multiple objects access new object instance then synchronization is not required?

https://docs.oracle.com/javase/tutorial/essential/concurrency/interfere.html states

Counter is designed so that each invocation of increment will add 1 to c, and each invocation of decrement will subtract 1 from c. However, if a Counter object is referenced from multiple threads, interference between threads may prevent this from happening as expected.

This is true if the multiple threads reference the same Counter object instance ? If multiple threads are each accessing the a new unique(to that thread) counter instance then synchronization is not required ?

Upvotes: 1

Views: 38

Answers (2)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279940

I'm going to quote from your link:

[...] However, if a Counter object is referenced from multiple threads, interference between threads may prevent this from happening as expected.

Interference happens when two operations, running in different threads, but acting on the same data, interleave. This means that the two operations consist of multiple steps, and the sequences of steps overlap.

If each of your threads has its own Counter instance, then they are not acting on the same data. Therefore, there is no interference and synchronization is not required.

Upvotes: 3

Vivin Paliath
Vivin Paliath

Reputation: 95518

Yes. If you are sure that they are unique instances, then you don't need to synchronize. You will only need to synchronize if multiple threads are accessing and modifying the the same instance (shared state).

Upvotes: 2

Related Questions