Versions Compared

Key

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

...

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("connectionstringconnection string");	 
        } 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("Error initializing connection");  
    }
    return dbConnection;
  }
	  
  public static void main(String[] args) {
    // ...
    Connection connection = getConnection();
  }
}

...

Code Block
bgColor#ccccff
public final class Lazy {
  private static Connection dbConnection;

  static {
    // Initialize a database connection
    try {
      dbConnection = DriverManager.getConnection("connectionstringconnection string");
    } catch (SQLException e) {
      dbConnection = null;	
    }        
    // Other initialization
  }

  // ...
}

...

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("connectionstringconnection string");
          return dbConnection;
        } catch (SQLException e) {
          return null;
        }
      }
    };
    
  public static Connection getConnection() {
    Connection connection = connectionHolder.get();
    if(connection == null) {
      throw new IllegalStateException("Error initializing connection");  
    }
    return connection;
  }

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

...