mercredi 10 mai 2017

Java - synchronized(MyClass.class){ } in Singleton Design Pattern - What does this do?

I'm learning design patterns and have intermediate experience in Java. I'm attempting to implement the Singleton design pattern and have come across the following code in a method:

    public static Singleton getInstance(){

    if( firstInstance == null ){
        if (firstThread){
            firstThread = false;
            Thread.currentThread();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
                Logger.getLogger(Singleton.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        synchronized(Singleton.class){

            if(firstInstance == null){
                firstInstance = new Singleton();
            }

        }


    }

    return firstInstance;
}

I understand how the method works, but I have a question with one specific part of this code:

        synchronized(Singleton.class){

            if(firstInstance == null){
                firstInstance = new Singleton();
            }
        }

I know that the synchronized block forces only this part of the code to be synchronized which makes the implementation thread-safe and doesn't slow down the whole method, but why are we wrapping Singleton.class in parenthesis before the access modifier synchronized?

My question is more Java-related than it is Design Pattern-related. I tried searching Google and StackOverflow, but I'm not sure what this is actually called which limits my results.

I hope you guys can help me out here.

Thanks in advance!

Aucun commentaire:

Enregistrer un commentaire