Versions Compared

Key

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

...

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

  private static final ThreadLocal<Connection> connectionHolder
    = new ThreadLocal<Connection>() {
        public Connection initialValue() {
          try {
            Connection conn = DriverManager.getConnection("connectionstring");
            flag = 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(flag);
  }
}

It is safe to set shared class variables from the initialValue() method. Consequently, each thread will see a consistent value of the flag field.

Risk Assessment

Starting and using background threads during class initialization can result in deadlock conditions.

...