The singleton mode is the simplest mode, but the lazy mode of the singleton mode will be thread unsafe when it is concurrent.
single thread
Singleton mode: Lazy mode thread is not safe
package com.wb.single; public class Single { private static Single single = null; private Single() { } public static Single getInstance() { if (null == single) { single = new Single(); } return single; } }
Hungry Man Mode: Thread Safety
package com.wb.single; public class Single1 { private static Single1 single1 = new Single1(); private Single1() { } public static Single1 getInstance() { return single1; } }
Safe Lazy Style:
package com.wb.single; public class Single2 { private static Single2 single2 = null; private Single2() { } public static Single2 getInstance() { if (null == single2) { synchronized (Single2.class) { if (null == single2) { single2 = new Single2(); } } } return single2; } }Do your best, Pikachu