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;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…