Is a synchronized static method legal in Java?

Is a synchronized static method legal in Java?

+2


source to share


2 answers


Yes. It acquires a lock on the object that represents the class in which the method is defined (e.g. MyClass.class)



+14


source


Yes, and it simplifies static factory methods like this:

class Foo {
    private Foo() {}

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

    private static Foo instance = null;
}

      

This is what it would look like if the methods static

couldn't be synchronized

:



class Foo {
    private Foo() {}

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

    private static Foo instance = null;

    private static final Object LOCK = Foo.class;
    // alternative: private static final Object LOCK = new Object();
}

      

Not that big a deal, it just saves 2 lines of code.

0


source







All Articles