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