java synchronized method - how does it work

2020-02-05 10:13发布

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

4条回答
ゆ 、 Hurt°
2楼-- · 2020-02-05 10:17

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.

查看更多
戒情不戒烟
3楼-- · 2020-02-05 10:19

multiple threads could call setValue method with different value. So if you really want to ensure that one threads change is visible to another thread then method should be synchronized.

查看更多
男人必须洒脱
4楼-- · 2020-02-05 10:33

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;
}
查看更多
男人必须洒脱
5楼-- · 2020-02-05 10:40

Synchronized method does two things:

  • Does not allow more than 1 thread to execute that method
  • Synchronizes thread memory cache with shared memory.

In your case only one thread will be able to update that variable and also all other threads will see up to date data in the variable balance.

Without synchronization other thread would user (that's very likely) their cached value of balance so you would get inconsistent balance value after program execution.

You can find very nice explanation of your problem in this presentation.

查看更多
登录 后发表回答