Java thread-safe Singleton Mode

Source: Internet
Author: User

Write a Singleton pattern)

Public final class eagersingleton
{
Private Static eagersingleton singobj = new eagersingleton ();
Private eagersingleton (){
}
 
Public static eagersingleton getsingleinstance (){
Return singobj;
}
}
This method is calledHunger ModeEvery object has been initialized before it is used. This may lead to potential performance problems: what if this object is large? Before using this object, loading it into the memory is a huge waste. In this case, we can improve the above Code and use a new design idea --Delayed Loading(Lazy-load Singleton ).

Public final class lazysingleton
{
Private Static lazysingleton singobj = NULL;
 
Private lazysingleton (){
}
 
Public static lazysingleton getsingleinstance (){
If (null = singobj) singobj = new lazysingleton ();
Return singobj;
}
}
This is the so-called lazy model. It uses delayed loading to ensure that objects are not initialized before they are used.Is this writing thread safe? Insecure. This is because multiple threads may run to If (null = singobj) at the same time, and singobj is determined to be null, so Initialization is performed at the same time.Therefore, the question is how to ensure the thread security of this Code? It's easy to add a synchronized before that method.

Public final class threadsafesingleton
{
Private Static threadsafesingleton singobj = NULL;
 
Private threadsafesingleton (){
}
 
Public staticSynchronizedThreadsafesingleton getsingleinstance (){
If (null = singobj) singobj = new threadsafesingleton ();
Return singobj;
}
}
Is there anything in this writing?Performance problemsWhat about it? The answer must be yes! The cost of synchronization will inevitably reduce the concurrency of the program to a certain extent. Is there any way, on the one hand, it is thread-safe, and can have a high degree of concurrency?

We have observed that the thread is not secure because the object is initialized. Therefore, we can try to reduce the synchronization granularity by only synchronizing the object during initialization. It is necessary to propose a new design concept --Double check lock(Double-checked lock ).

Public final class doublecheckedsingleton
{
Private Static doublecheckedsingletonsingobj = NULL;
 
Private doublecheckedsingleton (){
}
 
Public static doublecheckedsingleton getsingleinstance (){
If (null = singobj ){
Synchronized (doublecheckedsingleton. Class ){
If (null = singobj)
Singobj = new doublecheckedsingleton ();
}
}
Return singobj;
}
}
This method enables synchronization only when new objects are loaded. After loading, other threads can determine the cost of skipping the lock directly to 15th lines of code in the ninth line. Good concurrency.


The above code implements lazy-load on the one hand, and thread security with good concurrency on the other. Everything looks perfect. In fact, there is still a problem with this writing! Where is the problem?Assume that thread a executes row 9th and determines that the object is null. Therefore, thread a executes to row 12th to initialize the object, but initialization takes time, however, the object address already exists. At this time, thread B also executes the ninth line, which determines that it is not empty, so it jumps directly to 15 rows to get this object.However, this object has not been fully initialized! What is the use of a non-initialized object! About this double-checked
There are many discussions about lock. Currently, it is recognized as an anti-pattern and is not recommended!

 

A New Mode -- Initialization on demand holder is proposed here.Internal class to achieve delayed LoadingObject. When initializing this internal class, JLS (Java language sepcification) ensures the thread security of this class. This method is completely used.Java Virtual Machine mechanism for synchronization guarantee, there is no synchronization keyword.
Public class Singleton
{
Private Static class singletonholder
{
Public final static Singleton instance = new Singleton ();
}

Public static Singleton getinstance ()
{
Return singletonholder. instance;
}
}

Provide links for your reference:
Double-checked lock: http://en.wikipedia.org/wiki/Double-checked_locking
Initialation on demand holder:

Http://en.wikipedia.org/wiki/Initialization_on_demand_holder_idiom

 

Original post address: http://blog.sina.com.cn/s/blog_75247c770100yxpb.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.