How it works...

The key of the example is the getConnection() method and the private static class LazyDBConnection instance. When the first thread calls the getConnection() method, the LazyDBConnection class initializes the INSTANCE object by calling the constructor of the DBConnection class. This object is returned by the getConnection() method. When the rest of the threads call the getConnection() method, the object is already created, so all the threads use the same object that is created only once.

When you run the example, you will see the start and end messages of 20 tasks, but only one creation message.

Get Java 9 Concurrency Cookbook - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.