There are several distinct issues here:
Q: If multiple threads make overlapped calls to increment()
and decrement()
, and then they stop, and then enough time passes with no threads calling increment()
or decrement()
, will getValue() return the correct number?
A: Yes. The locking in the increment and decrement methods insures that each increment and decrement operation will happen atomically. They can not interfere with one another.
Q: How long is enough time?
A: That's hard to say. The Java language specification does not guarantee that a thread calling getValue() will ever see the latest value written by some other thread because getValue() accesses the value without any synchronization at all.
If you change getValue() to lock and unlock the same lock object or if you declare count to be volatile
, then zero amount of time would be enough.
Q: Can a call to getValue()
return an invalid value?
A: No, It can only ever return the initial value, or the result of complete increment()
call or the result of a complete decrement()
operation.
But, the reason for this has nothing to do with the lock. The lock does not prevent any thread from calling getValue()
while some other thread is in the middle of incrementing or decrementing the value.
The thing that prevents getValue() from returning a completely invalid value is that value is an int
, and the JLS guarantees that updates and reads of int
variables are always atomic.