Vinod Jayachandran
Vinod Jayachandran

Reputation: 3898

Comparison b/w Lazy loading with double check lock Vs Class level initialization

Assuming I have an empty constructor for a single ton class , which of the below 2 approaches is better to return an instance from a public getInstance method?

  1. Class level initialization {

    public class ClassName{
    
    private static ClassName instance = new ClassName ();
    }
    

    }

  2. Lazy loading with double check lock

    if (null == instance) {
    
            synchronized (this) {
        if(null == instance) {
            instance = new className();
                }
        }
    }
    

I was thinking Class level initialization wouldn't create any harm here. But would like to confirm it from the experts. Please help

Upvotes: 1

Views: 231

Answers (1)

Peter Lawrey
Peter Lawrey

Reputation: 533530

You should have a private constructor and a final instance field. Ideally the class should be final as well. The simplest way to do all this is to use an enum

public enum Singleton implements MyInterface {
    INSTANCE;
} 

Upvotes: 1

Related Questions