How to do it...

Follow these steps to implement the example:

  1. Create a class named DBConnectionOK:
        public class DBConnectionOK {
  1. Declare a private constructor. Write the name of the thread that executes it:
        private DBConnectionOK() {           System.out.printf("%s: Connection created.\n",                            Thread.currentThread().getName());         }
  1. Declare a private static class named LazyDBConnectionOK. It has a private static final DBConnectionOK instance named INSTANCE:
        private static class LazyDBConnection {           private static final DBConnectionOK INSTANCE = new                                                   DBConnectionOK();         }
  1. Implement the getConnection() method. It doesn't receive any parameter and returns a DBConnectionOK object. It returns the INSTANCE object:
 public static DBConnectionOK getConnection() ...

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.