Singleton
- There can be only one instance; You must create your own instance; this instance must be provided to all other objects
Implementation method A hungry man type singleton
Lazy-Singleton
DCL Singleton
However , because the Java compiler allows the processor to be executed in order (order reordering), the sequence of 2 and 3 points above is not guaranteed . (meaning that it may instance! = NULL when it is possible that the constructor is not actually initialized).
The workaround is to define instance as volatile . (Volatile has two semantics: 1. Guarantee the visibility of variables; 2. Prohibit reordering of instructions for this variable)
- Refer to <<java concurrent programming >> P286 ~ P287. In subsequent versions of JMM (>= Java5.0), the DCL can be initiated in a way that combines volatile, and this approach has a minimal impact on performance. However, the use of the DCL has been widely discarded.
- (Because the semantics of the volatile masking command reordering are fully fixed in JDK1.5, the previous JDK still does not completely avoid the problem caused by reordering even if the variable is declared volatile, mainly because the code before and after the volatile variable still has a reorder problem.) )
Static Inner class Singleton
Summary
- In view of the efficiency, safety and other problems, generally used a hungry man type singleton or static internal class singleton. The latter is a common method of singleton implementation.
[Java] [Singleton] [DCL]