Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
bgColor#FFcccc
public class Lazy {
  private static volatile boolean initialized = false;
  static {
    Thread t = new Thread(new Runnable() {
      public void run() {
        // Initialize, for example, a database connection
        initialized = true;
      }
    );
    
    t.start();
    try {
      t.join();
    } catch(InterruptedException ie) {
        throw new AssertionError(ie);
    }
    // Other initialization
  }
  public static void main(String[] args) {
    System.out.println(initialized);
  }
}

...

Code Block
bgColor#ccccff
public class Lazy {
  private static volatile boolean initialized = false;
  
  static {
    // Initialize, for example, a database connection
    initialized = true;
  }
  
  public static void main(String[] args) {
    System.out.println(initialized);
  }
}

...

Compliant Solution (ThreadLocal)

This compliant solution uses a ThreadLocal object to initialize a database connection and set the initialized flag to true depending on whether the initialization succeeded.

Code Block
bgColor#ccccff
public class Lazy {
  private static volatile boolean initialized = false;

  private static ThreadLocal<Connection> connectionHolder
    = new ThreadLocal<Connection>() {
        public Connection initialValue() {
          try {
          	  Connection conn = DriverManager.getConnection("connectionstring");
            initialized = true;
	    return DriverManager.getConnection("connection-string")conn;
	  } catch (SQLException e) {
	    initialized = false;
	    return null;
	  }
        }
  };
    
  public static Connection getConnection() {
    return connectionHolder.get();
  }

  public static void main(String[] args) {
    Connection conn = getConnection();
    System.out.println(initialized);
  }
}

...