mre mre - 1 year ago 75
Java Question

How to implement thread-safe lazy initialization?

What are some recommended approaches to achieving thread-safe lazy initialization? For instance,

// Not thread-safe
public Foo getInstance(){
if(INSTANCE == null){
INSTANCE = new Foo();

return INSTANCE;

Answer Source

For singletons there is an elegant solution by delegating the task to the JVM code for static initialization.

public class Something {
    private Something() {

    private static class LazyHolder {
            public static final Something INSTANCE = new Something();

    public static Something getInstance() {
            return LazyHolder.INSTANCE;


and this blog post of Crazy Bob Lee

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download