O'Reilly logo

Java 9 Concurrency Cookbook - Second Edition by Javier Fernández González

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required