Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bill pugh singleton, why thread safe?

Why is Bill Pugh's Singleton design pattern thread safe?

public class Logger {
    private Logger() {
        // private constructor
    }

    // static inner class - inner classes are not loaded until they are
    // referenced.
    private static class LoggerHolder {
        private static Logger logger = new Logger();
    }

    // global access point
    public static Logger getInstance() {
        return LoggerHolder.logger;
    }

    //Other methods
}
like image 377
user9549562 Avatar asked Jun 09 '18 06:06

user9549562


1 Answers

Lets take a look at the comments:

// static inner class - inner classes are not loaded until they are referenced.

The "loading" is the process of initialising the inner class (LoggerHolder).

"until they are referenced" means the inner class (LoggerHolder) is not initialised until the LoggerHolder.logger static field is referenced ("used somewhere") in this case.

So the call to getInstance() references LoggerHolder.logger and starts the initialisation of the LoggerHolder inner class.

The whole process of initialising a class is synchronised by the JVM.

From the relevant documentation:

Because the Java programming language is multithreaded, initialization of a class or interface requires careful synchronization

The implementation of the Java Virtual Machine is responsible for taking care of synchronization and recursive initialization

The initialisation of the static field:

private static Logger logger = new Logger();

is a part of the inner class initialisation and this whole initialisation process ("loading") is effectively synchronised by the JVM.

like image 87
The Bartman Avatar answered Oct 27 '22 17:10

The Bartman