Java – should I synchronize static volatile variables?

There are several questions about this problem, but most of them focus on this problem, because this is not the intention of the problem

If there is static volatility in my class:

private static volatile MyObj obj = null;

In the following methods, I do:

public MyObj getMyObj() {
    if (obj == null) {
        obj = new MyObj();// costly initialisation
    }
    return obj;
}

I need synchronization to ensure that only one thread writes to this field, or will any writes be immediately displayed to other threads evaluating the obj = = null condition?

In other words: does volatile make you have to access writes on static variables synchronously?

Solution

You certainly need some kind of lock to ensure that only one thread writes to the field Regardless of the volatility, both threads can "see" that obj is null, and then both threads begin to initialize with the current code

Personally, I will choose one of the following three options:

>Initialize when the class is loaded (knowing that this will be lazy, but not as lazy as before the first call to getmyobj):

private static final MyObj obj = new MyObj();

>Use unconditional locking:

private static MyObj obj;
private static final Object objLock = new Object();

public static MyObj getMyObj() {
    synchronized(objLock) {
        if (obj == null) {
            obj = new MyObj();
        }
        return obj;
    }
}

>Lazy using nested classes:

public static MyObj getMyObj() {
    return MyObjHolder.obj;
}

private static class MyObjHolder {
    static final MyObj obj = new MyObj();
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>