Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
161 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...