Singleton mode trap

Source: Internet
Author: User

Today, I went to jdon and saw its design research topic. Bang has several articles commenting on Singleton pattern, claiming "Singleton is edevil" (see http://www.jdon.com/jive/article.jsp? Forum = 91 & Thread = 17578), and cited several foreign pages to prove your point of view, one of which is to say that Singleton is not just a model, it is an anti-pattern.
Next I will talk about my views on Singleton mode. Analyze the singleton mode traps one by one to help you use the singleton mode correctly.
(1) Trap 1: performance bottleneck of function calling
In C ++, there is only one implementation method for a singleton (Java code is used in this article ):

Public class lazysingleton {
Private Static lazysingleton m_instance = NULL;
Private lazysingleton (){};
Synchronized public static lazysingleton getinstance (){
If (m_instance = NULL)
M_instance = new lazysingleton ();
Return m_instance;
}
}

Lazysingleton delays object initialization until it is called. To prevent multiple instances from being generated in a multi-threaded environment, use the synchronized keyword to ensure the thread security of the function getinstance call. The existence of the synchronized keyword ensures that only one object is generated, but it also becomes a performance bottleneck in a multi-threaded environment. A multi-threaded program has to wait in line to form a single-line Program Execution Process, which is intolerable in a high-concurrency environment. In C ++, the dual-check mechanism can be used to limit this performance problem only when the object is constructed for the first time. Java cannot use the dual-check mechanism.
However, Java can implement eagersingleton as follows:

Public class eagersingleton {
Private Static eagersingleton m_instance = new eagersingleton ();
Private eagersingleton (){};
Public static agersingleton getinstance (){
Return m_instance;
}
}

Compared with lazysingleton, eagersingleton puts the initialization of the object to the class loading. This avoids the performance bottleneck of the synchronized keyword.
(2) trap 2: Access mutually exclusive shared resources
Thread security issues should also be considered when access to mutex resources in eagersingleton. The following is an example: public class eagersingleton {
Private Static eagersingleton m_instance = new eagersingleton ();
Private hashmap map = new hashmap ();
Private eagersingleton (){};
Public static agersingleton getinstance (){
Return m_instance;
}
Public void refreshmap (Object key ){
Synchronized (MAP ){
If (! Map. Contains (key ))
Map. Put (Key, value); // value indicates the real-time data at this time.
}
}
}

This class is a singleton. multi-thread concurrent access to map and map is NOT thread-safe. You need to add thread-safe keywords. Otherwise, the trap of access to mutex resources is thrown.
(3) trap 3: Illegal logic trap
This situation is generally caused by misuse of the singleton mode. We will consider the abuse of Singleton. The following code is used to complete the operation process after getvaluebyname and printvalue immediately. Public class eagersingleton {
Private Static eagersingleton m_instance = new eagersingleton ();
Private string value = NULL;
Private eagersingleton (){};
Public static agersingleton getinstance (){
Return m_instance;
}
Synchronized public void getvaluebyname (string name ){
Value = getbynamefromdatebase (name );

}
Public viod printvalue (){
System. Out. println (this. vaue );
}
}

This class contains a private attribute value. In a multi-threaded environment, reasonable logic of the value cannot be guaranteed. After a thread getvaluebyname, the value is immediately printvalue. It is also possible that the value has been modified by other threads. This is an abuse of the singleton mode, which is not suitable for Singleton.
To eliminate the trap of illegal logic, you can reconstruct the class into a pure behavior class. The code after reconstruction is as follows:

Public class eagersingleton {
Private Static eagersingleton m_instance = new eagersingleton ();
Private eagersingleton (){};
Public static agersingleton getinstance (){
Return m_instance;
}
Private string getvaluebyname (string name ){
Return getbynamefromdatebase (name );

}
Public viod printname (string name ){
String value = getvaluebyname (string name );
System. Out. println (value );
}
}

You can call printname (string name) to directly complete the operation process, process the private attributes into procedural parameter passing, and change the class to a pure behavior class.

Classes that contain private attributes and assign values to them do not call this trap. assigning values to private attributes in the constructor does not cause illegal logic. The following code:

Public class eagersingleton {
Private Static eagersingleton m_instance = new eagersingleton ();
Private hashmap map = new hashmap ();

Private eagersingleton (){
Map. Put (Key, value); // value indicates the real-time data at this time.
}
Public static agersingleton getinstance (){
Return m_instance;
}
}

The constructor does not need to add thread security keywords to ensure thread security. Because the class loader is thread-safe, eagersingleton will only be instantiated once during class loading, in this way, the thread in singleton mode will not be unsafe or cause illegal logic.
(4) trap 4: transfer of Singleton traps
When an object is a private attribute of a singleton class, the trap will not only appear in the class itself, but also be passed to the class where the private object is located. See the following code:

Public class eagersingleton {
Private Static eagersingleton m_instance = new eagersingleton ();
Private newclass = nll;
Private eagersingleton (){
Newclass = new newclass ();
};
Public static agersingleton getinstance (){
Return m_instance;
}
Public viod printname (string name ){
String value = newclass. operationbynameandreturnvalue (string name );
System. Out. println (value );
}
}

At first glance, in the Code, except the constructor initializes the private property, there is no value assignment to the private property in other places, which will not cause illegal logic traps. In fact, this assignment operation may be implicitly performed in the newclass. operationbynameandreturnvalue (string name) operation. Only when the operationbynameandreturnvalue operation of newclass does not assign values to its private attributes can the true logic be guaranteed. Similarly, only by ensuring that the operationbynameandreturnvalue operation of newclass does not fall into the access mutex resource trap can eagersingleton not fall into this trap.
Method to eliminate this trap: (1) the name of the class method should be reasonable, for example, pure behavior method name: interprete, excute, methods such as operation should not contain direct or indirect value assignment operations on private attributes. The responsibilities of each method should be clear. (2) do not include instances of non-singleton classes as private attributes (except for container classes) in a singleton class. When an instance of the class must be a private attribute, review whether the class as a private property should also be designed as a singleton class; or ensure that the initialization value of this class is limited to the constructor.

 

Address: http://www.blogjava.net/JavaExplore/archive/2006/08/26/65914.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.