...
Noncompliant Code Example (background thread)
This In this noncompliant code example begins initializing the class Lazy
. The code , the statements in the static
block is responsible for initialization, and starts initializer start a background thread as part of class initialization. The background thread attempts to initialize a database connection but needs to wait until initialization of all members of the Lazy
class, including dbConnection
, has finished.
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("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);
}
// 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();
}
}
|
Wiki Markup |
---|
Recall that staticallyStatically-initialized fields are guaranteed to be fully constructed before becoming visible to other threads (see [CON26-J. Do not publish partially initialized objects] for more information). Consequently, the background thread must wait for the 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, threads should not be started 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 timers to that perform recurring tasks from within code responsible for initialization also results in creates liveness issues.
Compliant Solution (static
initializer, no background threads)
This compliant solution also uses a static
initializer for initialization and does not spawn a any background thread threads from it.
Code Block |
---|
|
public final class Lazy {
private static Connection dbConnection;
static {
// Initialize a database connection
try {
dbConnection = DriverManager.getConnection("connection string");
} catch (SQLException e) {
dbConnection = null;
}
// Other initialization (do not start any threads)
}
// ...
}
|
Compliant Solution (ThreadLocal
)
...
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;
}
}
};
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();
}
}
|
It is also safe to set The static initializer can still be used to initialize any other shared, class variables. Alternatively, the variables can be initialized from the initialValue()
method.
...
Wiki Markup |
---|
*CON03:EX1*: The {{ObjectPreserver}} class (based on \[[Patterns 02|AA. Java References#Patterns 02]\]) that is shown below: This class provides a mechanism for storing object references, which prevents an object from being garbage-collected, even if the remainingobject programis nonot longerdereferenced maintains a reference to in the objectfuture. |
Code Block |
---|
|
public final class ObjectPreserver implements Runnable {
private static ObjectPreserver lifeLine = new ObjectPreserver();
private ObjectPreserver() {
Thread thread = new Thread(this);
thread.setDaemon(true);
thread.start(); // Keep this object alive
}
// Neither this class, nor HashMap will be garbage collected.
// References from HashMap to other objects will also exhibit this property
private static final ConcurrentHashMap<Integer,Object> protectedMap
= new ConcurrentHashMap<Integer,Object>();
public synchronized void run() {
try {
wait();
} catch(InterruptedException e) {
Thread.currentThread().interrupt(); // Reset interrupted status
}
}
// Objects passed to this method will be preserved until
// the unpreserveObject method is called
public static void preserveObject(Object obj) {
protectedMap.put(0, obj);
}
// Returns the same instance every time
public static Object getObject() {
return protectedMap.get(0);
}
// Unprotect the objects so that they can be garbage collected
public static void unpreserveObject() {
protectedMap.remove(0);
}
}
|
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 referencing the object, and the thread itself waits indefinitelyusing the current instance of the class. The thread waits indefinitely using a wait()
call. Consequently, this object exists for the remainder of the JVM's lifetime; however, as it . Because the object is managed by a daemon thread, the thread (and object) do does not hinder a normal shutdown of the JVM.
...