Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: changed exception string

...

Code Block
bgColor#FFcccc
public final class Lazy {
  private static Connection dbConnection;
	  
  static {
    Thread dbInitializerThread = new Thread(new Runnable() {
      public void run() {
        // Initialize the database connection
        try {
          dbConnection = DriverManager.getConnection("connectionstring");	 
        } catch (SQLException e) {
          dbConnection = null;	
	}
      }
    });
	    
    dbInitializerThread.start();
    try {
      dbInitializerThread.join();
    } catch(InterruptedException ie) {
      throw new AssertionError(ie);
    }
    // Other initialization   
  }
	  
  public static Connection getConnection() {
    if(dbConnection == null) {
      throw new IllegalStateException("ConnectionError notinitializing initializedconnection");  
    }
    return dbConnection;
  }
	  
  public static void main(String[] args) {
    // ...
    Connection connection = Lazy.getConnection();
  }
}

...

Code Block
bgColor#ccccff
public final class Lazy {
  private static final ThreadLocal<Connection> connectionHolder
    = new ThreadLocal<Connection>() {
      public Connection initialValue() {
        try {
          Connection dbConnection = DriverManager.getConnection("connectionstring");
          return dbConnection;
        } catch (SQLException e) {
          return null;
        }
      }
    };
    
  public static Connection getConnection() {
    Connection connection = connectionHolder.get();
    if(connection == null) {
      throw new IllegalStateException("ConnectionError notinitializing initializedconnection");  
    }
    return connection;
  }

  public static void main(String[] args) {
    // ...
    Connection connection = getConnection();
  }
}

...