There are many ways to write singletons, and this example is a way to write lazy singletons. What should be noted in high concurrency environments:
1. When a singleton accesses concurrently and calls its corresponding getInstance method, it will also cause multiple instance objects to be created, and locking is necessary.
2. Using synchronized is a better solution. The advantage is that the code is concise, and the disadvantage is that the maintenance cannot be handled and maintained when throwing an exception, so the system is in a good state.
3. The displayed lock settings are a good solution.
The code using lock is as follows:
package demo; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * Reference usage* @author Watson_Xu * @date 2012-1-8 04:31:09 pm */ public final class SingletonContext { private static SingletonContext sc = null; private SingletonContext() { } private static Lock lock = new ReentrantLock(); public static SingletonContext getInstance() { if(sc == null) { lock.lock(); if(sc == null) { try{ sc = new SingletonContext(); } finally { lock.unlock(); } } return sc; } }When using synchronized, the code is as follows:
package demo; /** * Reference to use * @author Watson_Xu * @date 2012-1-8 04:31:09 pm */ public final class SingletonContext { private static SingletonContext sc = null; private SingletonContext() { } public static synchronized SingletonContext getInstance() { if(null == sc) { sc = new SingletonContext(); } return new SingletonContext(); } }To view more Java syntax, you can follow: "Thinking in Java Chinese Manual", "JDK 1.7 Reference Manual Official English Version", "JDK 1.6 API java Chinese Reference Manual", "JDK 1.5 API java Chinese Reference Manual". I also hope that everyone will support Wulin.com more.