Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should you synchronize access to properties in Java? [duplicate]

I've recently stumbled upon an article titled Synchronize access to mutable fields. It claims that:

For example, in a multi-threaded environment, all get and set methods for mutable fields should usually be synchronized methods. This includes primitive fields.

My question is why? What would be the use of synchronizing getId method? Or what could happen if I don't synchronize it.

For example I pass a UserContext to a Spring Service function and call getUserId within the function. Could this be a problem if getUserId is not synchronized?

like image 990
Nux Avatar asked Dec 13 '17 14:12

Nux


Video Answer


1 Answers

My question is why?

To ensure memory visibility across threads.

What would be the use of synchronizing getId method?

Every synchronized getId call guarantees that the given id is up-to-date for the moment of ending of the operation (releasing a lock).

Or what could happen if I don't synchronize it?

A stale getId value will be used to update others variables which will affect correctness.


Every method that operates with the shared state of a variable needs some kind of synchronisation. The getter provides the state, so synchronisation is required. The setter changes the state, synchronisation is also required.

Imagine a thread that changes an id (a writer), and a thread that reads that id (a reader). If these threads don't synchronize their operations by the same lock, weird things may happen when the threads are running simultaneously:

  1. The reader reads the variable while a writer is in the middle of its execution.
  2. The reader can see a partially (or incorrectly) initialized/set value.
  3. The state can be out-of-date for the reader.
like image 184
Andrew Tobilko Avatar answered Sep 30 '22 09:09

Andrew Tobilko