...
Code Block | ||
---|---|---|
| ||
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 | ||
---|---|---|
| ||
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 | ||
---|---|---|
| ||
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(); } } |
...