Wednesday, August 3, 2016

How to implement a safe thread Singleton in Java

The sample below shows you one of the best ways to implement a Singleton in Java by marking the singleton class(Logger in our example) constructor as private and using getInstance() method in order to invoke the class instance created previously thanks to the static inner class LoggerHolder.

public class Logger {
private Logger() {
// private constructor
}
public static class LoggerHolder {
public static Logger logger = new Logger();
}
public static Logger getInstance() {
return LoggerHolder.logger;
}
public void log(String s) {
// log implementation
System.err.println(s);
}
}

No comments:

Post a Comment