We haven’t updated for some time. Recently, we have been busy preparing for the interview. During the preparation process, we found that we still need to accumulate so much
Singleton pattern -DCL
Double-checking checks, using the volatile keyword to prohibit instruction reordering, and creating secure singletons in multithreaded situations, directly to code
Private volatile static Instance Instance; private volatile static Instance Instance; private volatile static Instance Instance; private String instName; private Instance() { instName = "DCL"; } public static Instance getInstance() { if (instance == null) { synchronized (Instance.class) { if (instance == null) { instance = new Instance(); } } } return instance; }}Copy the code
Singleton pattern – Inner class
Singleton objects are constructed using inner classes, and the JVM guarantees singleton
public class Instance { private static class InstanceObj { private static final Instance INSTANCE = new Instance(); } public static Instance getInstance() { return InstanceObj.INSTANCE; }}Copy the code