There are several different issues here:
Q: If multiple threads make overlapping calls to increment() and decrement() , and then they stop, and then enough time, without threads calling increment() or decrement() , getValue () returns the correct number
A: Yes. Blocking increment and decrement methods ensures that every increment and decrement operation will occur atomically. They cannot interfere with each other.
Q: How long is enough time?
A: It's hard to say. The Java language specification does not guarantee that the thread calling getValue () will never see the last value written by some other thread, because getValue () accesses the value without any synchronization whatsoever.
If you modify getValue () to lock and unlock the same lock object, or if you declare count equal to volatile , then a zero amount of time will suffice.
Q: Can calling getValue() return an invalid value?
A: No. It can return only the initial value or the result of a full call to increment() or the result of the full operation decrement() .
But the reason for this has nothing to do with blocking. Locking does not prevent any thread from calling getValue() , while some other thread is in the middle of increasing or decreasing the value.
What prevents getValue () from returning a completely invalid value is an int value, and JLS ensures that updates and readings of int variables are always atomic.
source share