Versions Compared

Key

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

...

Code Block
bgColor#FFcccc
public class Lazy {
  private static int number;
  private static Connection conn;
	  
  static {
    Thread t = new Thread(new Runnable() {
      public void run() {
        // Initialize, a database connection
        try {
	  conn = DriverManager.getConnection("connectionstring");
	} catch (SQLException e) {
	  conn = null;	
	}
	Lazy.this.number = 42;
      }
    });
	    
    t.start();
    try {
      t.join();
    } catch(InterruptedException ie) {
      throw new AssertionError(ie);
    }
    // Other initialization
    number = 42;
  }
	  
  public static Connection getConnection() {
    if(conn == null) {
      throw new IllegalStateException("Connection not initialized");  
    }
    return conn;
  }
	  
  public static void main(String[] args) {
    System.out.println(number);
  }
}

...

Code Block
bgColor#ccccff
public class Lazy {
  private static int number;
  private static Connection conn;

  static {
    // Initialize, a database connection
    try {
      conn = DriverManager.getConnection("connectionstring");
    } catch (SQLException e) {
      conn = null;	
    }        
    // Other initialization
    number = 42;
  }

  // ...
}

Compliant Solution (ThreadLocal)

This compliant solution uses a ThreadLocal object to initialize a database connection and sets flag to true depending on whether the initialization succeeds. The number field is initialized independently in a static initializer.

Code Block
bgColor#ccccff
public class Lazy {
  private static boolean flag;
  private static int number;

  static {
    number = 42;   
  }

  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) {
          flag = false;
          return null;
        }
      }
    };
    
  public static Connection getConnection() {
    return connectionHolder.get();
  }

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

...