简体   繁体   中英

Thread safe singleton and inner class solution

This is how I always created a thread-safe singleton, in order to use it in a multi-threading app.

public class Logger {

    private Logger() {}

    private static Logger instance = new Logger();

    public static Logger getInstance() {
        return instance;
    }

    public void log(String s) {
        // Log here
    }
}

Today I was studying to take my Java certification and on the book I found this other solution:

public class Logger {

    private Logger() {}

    private static Logger instance;

    private static class LoggerHolder {
        public static Logger logger = new Logger();
    }

    public static Logger getInstance() {
        return LoggerHolder.logger;
    }

    public void log(String s) {
        // Log here
    }
}

They don't mention about the other one.

What's better? And what's the difference between the two solution?

The second example is less likely to create an instance just because you accessed the class. Instead you would have to access the inner class. This level of paranoia makes sense for the JDK Library designers but in a more controlled code base, it is over the top IMHO.

I prefer simplicity and would use this instead

public enum MyLogger {
    INSTANCE;

    public void log(String s) {
       // log here
    }
}

I recommend strongly against creating a class called Logger There is already enough confusion over the many implementations of this class available including one builtin.

The second one is lazy. If, by some miracle, the program loads the class but never calls getInstance() , the logger instance, which might be an expensive object to create, won't be created.

Frankly, if a singleton is really needed (and with dependency injection frameworks, they're almost always unneeded), I prefer the first solution, which is easier to understand. I've rarely, if ever, seen a singleton whose class was loaded but which was never used in real code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM