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