...
Code Block | ||
---|---|---|
| ||
public final class Lazy {
private static Connection dbConnection;
// Other fields ...
static {
Thread dbInitializerThread = new Thread(new Runnable() {
public void run() {
// Initialize the database connection
try {
dbConnection = DriverManager.getConnection("connection string");
} catch (SQLException e) {
dbConnection = null;
}
}
});
// Other initialization, for example, start other threads
dbInitializerThread.start();
try {
dbInitializerThread.join();
} catch(InterruptedException ie) {
throw new AssertionError(ie);
}
}
public static Connection getConnection() {
if(dbConnection == null) {
throw new IllegalStateException("Error initializing connection");
}
return dbConnection;
}
public static void main(String[] args) {
// ...
Connection connection = getConnection();
}
}
|
Wiki Markup |
---|
Statically-initialized fields are guaranteed to be fully constructed before they are becomingmade visible to other threads (see [CON26-J. Do not publish partially initialized objects] for more information). Consequently, the background thread must wait for the main (or foreground) thread to finish initialization before it can proceed. However, the {{Lazy}} class's main thread invokes the {{join()}} method which waits for the background thread to finish. This interdependency causes a class initialization cycle that results in a deadlock situation. \[[Bloch 05b|AA. Java References#Bloch 05b]\] |
Similar to this noncompliant code example, it is inappropriate to start threads from constructors. See CON14-J. Do not let the "this" reference escape during object construction for more information. Starting Creating timers that perform recurring tasks and starting them from within code responsible for initialization also creates liveness issues.
Compliant Solution (static
initializer, no background threads)
This compliant solution also uses a static
initializer for initialization and does not spawn any background threads from it. All fields are initialized in the main thread.
Code Block | ||
---|---|---|
| ||
public final class Lazy {
private static Connection dbConnection;
// Other fields ...
static {
// Initialize a database connection
try {
dbConnection = DriverManager.getConnection("connection string");
} catch (SQLException e) {
dbConnection = null;
}
// Other initialization (do not start any threads)
}
// ...
}
|
...
Code Block | ||
---|---|---|
| ||
public final class Lazy { private static final ThreadLocal<Connection> connectionHolder = new ThreadLocal<Connection>() { public Connection initialValue() { try { Connection dbConnection = DriverManager.getConnection("connection string"); return dbConnection; } catch (SQLException e) { return null; } } }; // Other fields ... static { // Other initialization (do not start any threads) } 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(); } } |
The static initializer can still be used to initialize any other shared, class variablesfields. Alternatively, the variables fields can be initialized from the initialValue()
method.
...
This is a singleton class (see CON23-J. Address the shortcomings of the Singleton design pattern for more information on how to defensively code singleton classes). The initialization creates a background thread using the current instance of the class. The thread waits indefinitely using a by invoking Object.wait()
call. Consequently, this object exists for the remainder of the JVM's lifetime. Because the object is managed by a daemon thread, the thread does not hinder a normal shutdown of the JVM.
...