As explained in other answers, your code is not Thread safe since static method increment()
locks Class monitor and non-static method decrement()
locks Object monitor.
For this code example, better solution exists without synchronzed
keyword usage.
You have to use AtomicInteger to achieve Thread safety.
Thread safe using AtomicInteger
:
import java.util.concurrent.atomic.AtomicInteger;
class ThreadSafeClass extends Thread {
private static AtomicInteger count = new AtomicInteger(0);
public static void increment() {
count.incrementAndGet();
}
public static void decrement() {
count.decrementAndGet();
}
public static int value() {
return count.get();
}
}
increment
) it'd be thread safe. Or if you used some locking object. As I said, I don't know about Java - my comment stems from C# knowledge.synchronized
should be used only in static methods. So in my opionion even if you removes theincrement
method, it's still not threadsafe since two instances (which have only synchronized access through the same instance) can call the method concurrently.