Detailed Explanation of the Writing Method of Java Single Example

  • 2021-11-10 09:49:27
  • OfStack

Catalog Hungry Type Lazy Type 1 Lazy Type 2 Lazy Type 3 (Double Check) Static Internal Class Enumeration Summary

Singleton pattern, as its name implies, is that there is only one instance saved globally and it can avoid manual instantiation by users. Therefore, all kinds of writing methods of singleton pattern have one thing in common, and objects cannot be created by new keyword. Therefore, if it can be instantiated by constructor, then 1 must declare it private.

Hungry Han style


public class PersonResource {
    public static final PersonResource PERSON_RESOURCE_SINGLETON = new PersonResource();
    private PersonResource(){}
    public  static PersonResource getInstance() {
        return PERSON_RESOURCE_SINGLETON;
    }
}

This is the safest and simplest way to do this, but it has one drawback, that is, whether the instance is used or not, it will be instantiated, which is quite a waste of resources

Lazy type 1

Since the first one is a waste of resources, let's write it another way and let the class be instantiated when it is called


public class PersonResource {
    private static PersonResource personResourceSingleton;
    private PersonResource() {
    }
    public static PersonResource getPersonResourceSingleton(){
        if(null==personResourceSingleton){
            personResourceSingleton = new PersonResource();
        }
        return personResourceSingleton;
    }
}

This method can be initialized when the instance is needed, and it can run well under single thread, but it is easy to have problems if it is multi-threaded.

Lazy Style 2


public class PersonResource {
    private static PersonResource personResourceSingleton;
    private PersonResource() {
    }
    public static PersonResource getPersonResourceSingleton(){
        if(null==personResourceSingleton){
            personResourceSingleton = new PersonResource();
        }
        return personResourceSingleton;
    }
}

Multithreading is problematic because multiple threads can execute the getPersonResourceSingleton method concurrently, causing problems in determining whether it is null or not.

In this case, add a lock to make it mutually exclusive. There is another problem here. Every time you get an instance, you need to lock and unlock it. When an instance has been generated, it is redundant to lock it again.

Lazy Style 3 (Double Check)


public class PersonResource {
    private PersonResource(){    }
    private volatile static PersonResource personResource;
    public  static PersonResource getInstance(){
        if(personResource==null){
            synchronized (PersonResource.class){
                if(personResource==null){
                    personResource = new PersonResource();
                }
            }
        }
        return personResource;
    }
}

Since it is determined that there is no need to lock after the instance is generated, we can solve the problem by judging whether there is an instance once before acquiring the lock

Static inner class


public class PersonResource {
    private PersonResource(){}
    private static class PersonResourceHolder{
        public static PersonResource personResourceSingleton = new PersonResource();
    }
    public static PersonResource getInstance(){
        return PersonResourceHolder.personResourceSingleton;
    }
}

In addition to the single exception that double checking can ensure safety, it is also possible to hold singletons with a static inner class. The static inner class ensures that it will not be loaded with the loading of external classes, which ensures delayed loading. At the same time, instantiating singletons when loading classes ensures thread safety;

Enumerate


public enum PersonResource {
    /**
     * PersonResource Singleton 
     */
    personResource;
    public void setPersonResource(){
    }
}

The above methods are basically enough, but they all have a common shortcoming. Facing serialization and deserialization, it is impossible to guarantee singleton, but the characteristics of enumeration can guarantee this one point

Summarize

This article is here, I hope to give you help, but also hope that you can pay more attention to this site more content!


Related articles: