0

I have read that synchronized void f() { /* body */ } is equivalent to
void f() { synchronized (this) { /* body */ } }.

So when we do a synchronization of a singleton's get method what object are we synchronizing on. Is it the Class or is it the Object?

public class YourObject {
    private static YourObject instance;

    private YourObject() { }

    public static synchronized YourObject getInstance() {
        if (instance == null) {
            instance = new YourObject();
        }
        return instance;
    }
}

Is this equivalent to -

public static YourObject getInstance() {
    synchronized (this) {
        /* body */
    }
}

or

public static YourObject getInstance() {
    synchronized (YourObject.class) {
        /* body */
    }
}
6

2 Answers 2

2

Let's ask the documentation:

You might wonder what happens when a static synchronized method is invoked, since a static method is associated with a class, not an object. In this case, the thread acquires the intrinsic lock for the Class object associated with the class. Thus access to class's static fields is controlled by a lock that's distinct from the lock for any instance of the class.

So:

public static YourObject getInstance() {
    synchronized (YourObject.class) {
        /* body */
    }
}

is equivalent to you code

1

You are obtaining lock at class level i.e. static method in your synchronized method, so synchronization on YouObject.class is equivalent to static method synchronization. Also you won't be able to refer to this in your static method as this refers to the current or this object.

So this:

public static synchronized YourObject getInstance() {

in above code is equivalent to

synchronized (YourObject.class) {

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.