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
andset
methods for mutable fields should usually besynchronized
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?
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With