The Perfect Singleton mode (The Perfect Singleton)

Source: Internet
Author: User

The Perfect Singleton mode (The Perfect Singleton)
The PerfectSingleton

From time to time, I met Java programmers who are not actually sure how they should implement the singleton mode.

I don't consider the proper implementation in the thread environment. However, with most of the common implementation methods you can find on the network, you can easily create multiple Singleton implementations you want.

Suppose you have the following common Singleton implementation:

public final class NonSafeSingletonimplements Serializable {    private static final NonSafeSingleton INSTANCE = new NonSafeSingleton();    private NonSafeSingleton() {}    public static NonSafeSingleton getInstance() {       return INSTANCE;    }}

Now, note thatSerializableThis word. Think about it ..... You are right. If you send the above Code through RMI, you will get the second instance. It should be enough for serialization and deserialization in memory. You have just violated the singleton rule. That's not good. But how to fix it? Generally, two methods are used:

1. Difficult method (if you use Java1.4 or an older version)

You need to implement a readResolve method in your Singleton class. This is usually used to override the content already created by the serialization mechanism. In this method, the returned data is used to replace the serialized data. Here you only need to return your instance:

...    protected Object readResolve() throws ObjectStreamException {        return INSTANCE;    }...

2. Simple Method (if you use Java1.5 or an updated version)

Change your Singleton class to the enumeration type, and then remove the private constructor and getInstance methods. Below, it is really simple. Then you will get the following for free:

public enum SafeSingleton implements Serializable {     INSTANCE;}

Remember this when you implement the singleton mode. If you use RMI a lot, it can make your life easier.

Reference:The Perfect Singleton fromour JCG partner MarekPiechut at the Development worldstories.

Related Articles:

§ The dreaded double checked locking idiom in Java
§ Java Secret: Using an enum to build a State machine
§ Dependency Injection-The manual way
§ Java Generics Quick Tutorial
§ How does JVM handle locks

Note:

When this article was published on the concurrent programming network, I Will paste several important comments here, which will also give you some inspiration:

Comment 1:

If you consider threads, this kind of Singleton is the best I have ever seen in initialization-on-demand holder idiompublic class SingletonInitiOnDemand {private SingletonInitiOnDemand (){}; private static class SingletonHolder {private static final SingletonInitiOnDemand INSTANCE = new SingletonInitiOnDemand ();} public static SingletonInitiOnDemand getInstance () {return SingletonHolder. INSTANCE ;}}

Answer:

This method uses the internal class mechanism to implement delayed loading and thread security.

Comment 2:

public enum SafeSingleton implements Serializable {INSTANCE;}

Can you explain the implementation principle of this code?
Do I need a new INSTANCE in the code? For example:

private static final NonSafeSingleton INSTANCE = new NonSafeSingleton;

Answer:

The principle mechanism of this Code is the principle mechanism of enmu. The enmu object does not require new. I will write an example below and you will understand it.

enum SafeSingleton implements Serializable {INSTANCE;public void println() {System.out.println(“t”);}}public class Testt {public static void main(String[] args) {SafeSingleton singleton = SafeSingleton.INSTANCE;singleton.println();}}
You can also view more comments http://ifeve.com/perfect-singleton/ in the Concurrent Programming Network

Related Article

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.