// Non-thread security. This processing method works well in single-thread mode, but may cause problems in multi-thread mode. If the first thread finds that the member variable is null, it is ready to create an object. This is the second thread, and it also finds that the member variable is null, it also creates a new object. This results in multiple Singleton instances in one JVM. If the member variables of this Singleton type change during the running process, it may cause inconsistency among multiple Singleton type instances, resulting in some strange phenomena. For example, a service process stops multiple thread services by checking a certain attribute of the singleton object. If there are instances of multiple Singleton objects, some thread services will stop, some thread services cannot be stopped
public class TestService{ private static TestService instance = null;
private TestService() {
}
public static TestService getInstance() { if (instance == null) { instance=new TestService(); } return instance; } } |
// Thread security this processing method introduces the synchronization code, but because this synchronization code will only be executed once or multiple times at the beginning, the performance of the entire system will not be affected.
public class TestService{ private static TestService instance = null;
private TestService() {
}
private static synchronized void syncInit() { if (instance == null) { instance = new TestService(); } }
public static TestService getInstance() { if (instance == null) { syncInit(); } return instance; } } |