Versions Compared

Key

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

...

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

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 conn;
	  } catch (SQLException e) {
	    return null;
	  }
        }
  };
    
  public static Connection getConnection() {
    return connectionHolder.get();
  }

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

...