On the Design Model-singleton Model
Import java. io. serializable; public class Singleton implements Serializable {private Singleton () {} private static class SingletonHolder {private static final Singleton INSTANCE = new Singleton ();} public static Singleton getInstance () {return SingletonHolder. INSTANCE;} private Object readResolve () {return SingletonHolder. INSTANCE ;}}
What is the difference between the above Code?
Let's first recall the advantages and disadvantages of the Order example mode:
Lazy mode: There is an object lock. Lock competition has a certain impact on performance.
Hunger mode: Initialize the singleton object at the beginning. If the initialization time of the singleton object is long (large object), the time consumed for class loading is increased.
The above Code uses internal classes. When classes are loaded, the singleton object is not initialized and the singleton object is initialized for the first time. Due to the loading mechanism of internal classes, solved the lock problem,
Here, the reader can already know the role of the internal class, but there is another difference that is not mentioned, but the private method is added.
Oh, by the way, let's take a look at the test results:
The result is True, which is incredible,
Yes. This method solves the problem of serialization destroying the singleton mode.
Legacy: reflection can destroy the singleton Mode
Zookeeper