简体   繁体   中英

Is synchronized static method legal in Java?

Java中的同步静态方法是否合法?

Yes. It gets the lock on the object representing the class the method is defined in (eg MyClass.class)

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;
}

Here's what it might look like if static methods could not 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM