During the interview, the interviewer has to add a volatile for the singleton class in the multithreaded environment with handwritten on-demand loading.

went to the interview last week, handwritten singleton class

then I handwritten a more commonly used global setting class:


import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Setting {

    private static Setting setting;

    private  static Lock lock = new ReentrantLock();

    private Setting(){

    }

    public static Setting get() {
        if(setting != null) {
            return  setting;
        }

        lock.lock();
        if(setting == null) {
            setting = new Setting();
        }
        lock.unlock();

        return setting;
    }
}

as a result, the interviewer said that this single case would go wrong when the JVM command was reordered, and that he had to add a volatile, to the setting object at that time, and now he was very confused. My rookie, would you like to analyze it?

Apr.01,2021

http://chen-tao.github.io/201.


instruction reordering is to optimize instructions and improve program efficiency.
for example, instance = new Singleton () can be decomposed into:

1memory = allocate();   // 
2ctorInstance(memory);  //   
3instance = memory;     // instance

if the third line of code does not depend on the second line of code, the JVM will be reordered:

1memory = allocate();   // 
2instance = memory;     // instance
3ctorInstance(memory);  //   

the code after reordering has no effect in the case of single thread, but the execution order of multi-thread is as follows:
thread A:

lock.lock();
if(setting == null) {
    //Ainstance = memory;settingB
    setting = new Setting(); 
}

Thread B:

if(setting != null) {
    // ctorInstance(memory);
    return  setting; 
}

workaround:
private static Setting setting; change to private static volatile Setting setting;
volatile is a feature added after jdk1.5, which can prohibit variables from using reordering.
codeword is not easy, it is useful to adopt

.
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1eacac9-20f5.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1eacac9-20f5.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?