Sign in to follow this  
scottrick49

[java] static synchronized question

Recommended Posts

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?

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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++;
}

}


Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this