[java] static synchronized question

Started by
1 comment, last by FlaiseSaffron 14 years, 1 month ago
class testClass {
static int counter = 0;

synchronized void bump() {
counter++;
}

static synchronized void staticBump() {
counter++;
}
}
Will these two methods be synchronized correctly? (so the static method and the instanced method will not both modify the counter at the same time?) My initial thought was yes, this will work, but after doing some more reading I'm starting to think that this isn't synchronizing as I hoped: The instance method bump() will be synchronized on the current testClass object that is instantiated, while the static method will be synchronized on the testClass Class object. Since they're not the same object, they could execute simultaneously, and screw stuff up. Is that right?
scottrick49
Advertisement
I think you are right. You could call staticBump from bump() (which could then be unsynchronised). Another idiom in Java: you can create a new static object that is private to the class, and synchronise on it:
class TestClass {    private static final Object lock = new Object();    private static int counter = 0;    void bump() {        synchronized(lock) {            counter++;        }    }    static void staticBump() {        synchronized(lock) {            counter++;        }    }}

This would be used for more complex cases (protecting an entire class invariant, possibly across more than one instance). It also reduces potential lock contention, but this generally doesn't do much unless you are in the habit of synchronising over random Class instances from other classes, which isn't great style to begin with.

In this specific instance, you could replace the counter with an AtomicInteger.
No. The static method will synchronize around the static class object. You would need to do this:

class TestClass {	static int counter = 0;	void bump() {		synchronized(TestClass.class) {			counter++;		}	}	static synchronized void staticBump() {		counter++;	}}

This topic is closed to new replies.

Advertisement