Why is this class not thread safe?
Since the increment
method is static
it will synchronize on the class object for the ThreadSafeClass
. The decrement
method is not static and will synchronize on the instance used to call it. I.e., they will synchronize on different objects and thus two different threads can execute the methods at the same time. Since the ++
and --
operations are not atomic the class is not thread safe.
Also, since count
is static
, modifying it from decrement
which is a synchronized instance method is unsafe since it can be called on different instances and modify count
concurrently that way.
You have two synchronized methods, but one of them is static and the other is not. When accessing a synchronized method, based on it's type (static or non-static), a different object will be locked. For a static method, a lock will be put on the Class object, while for the non-static block, a lock will be put on the instance of the class that runs the method. Because you have two different locked objects, you can have two threads that modify the same object simultaneously.
Can anyone explain why above class is not thread safe?
-
increment
being static, synchronization will be done on the class itself. -
decrement
being not static, synchronization will be done on the object instantiation, but that doesn't secure anything ascount
is static.
I'd like to add that to declare a thread-safe counter, I believe the simplest way is to use AtomicInteger
instead of a primitive int.
Let me redirect you to the java.util.concurrent.atomic
package-info.