Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (7k points)

What are some recommended approaches to achieve thread-safe lazy initialization?

1 Answer

0 votes
by (13.1k points)

For singletons, you can delegate 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;

    }

}

If you are using Apache Commons Lang, then you can use the variations o ConcurrentInitializer like LazyInitializer.

ConcurrentInitializer<Foo> lazyInitializer = new LazyInitializer<Foo>() {

        @Override

        protected Foo initialize() throws ConcurrentException {

            return new Foo();

        }

    };

You can now safely get Foo( gets initialized only once)

Foo instance = lazyInitializer.get();

Want to learn Java? Check out the core java certification from Intellipaat.

Related questions

0 votes
1 answer
asked Mar 8, 2021 in Java by dante07 (13.1k points)
0 votes
1 answer
0 votes
1 answer
asked Mar 30, 2021 in Java by Jake (7k points)

Browse Categories

...