Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java synchronized method - how does it work

I think I know this, but would like it confirming.

Obviously the synchronized blocks other threads from accessing it, but I see and awful lot of examples such as

   public synchronized void setValue(int value)
   {
       balance=value;
   }

Am I right in thinking, that if the method only does one line like the above, then there is no point in it being synchronized.

Thanks

like image 252
Matthew Smith Avatar asked Jan 09 '13 18:01

Matthew Smith


2 Answers

Am I right in thinking, that if the method only does one line like the above, then there is no point in it being synchronized.

No. You seem to believe that synchronized only means atomicity.

But it actually provides more than that - in particular, it guarantees:

  • atomicity, which is not useful for a one line assigment (except in border case below)
  • visibility
  • prevents reordering
  • mutual exclusion: 2 methods synchronized on the same monitor can't be run concurrently

In your example, without synchronized, you have no guarantee that if a thread calls your method and another reads balance subsequently, that second thread will see the updated value.

Note that visibility must be ensured at both ends: the write AND the read need to be synchronized, with the same monitor. So the getter getBalance will need to be syhcnronized too.

Border case: double and long assignements are not guaranteed to be atomic. So even on a one line example like below, without the synchronized keyword, it would be possible that one thread updates the first 32 bits of the double and another thread updates the last 32 bits, creating a new mixed up balance variable.

public synchronized void setValue(double value) {
    balance = value;
}
like image 115
assylias Avatar answered Oct 26 '22 17:10

assylias


It doesn't only block other threads accessing this method : it blocks other threads accessing any block or method with the same lock (here the instance).

The point is that if another synchronized method is longer, you'll be assured this one won't be run at the same time.

This is important if the other method relies on the balance variable not changing during its execution.

like image 37
Denys Séguret Avatar answered Oct 26 '22 17:10

Denys Séguret