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?