...
Code Block |
---|
|
public class Lazy {
private static boolean initialized = false;
static {
Thread t = new Thread(new Runnable() {
public void run() {
// Initialize, for example, a database connection
initialized = true;
}
);
t.start();
try {
t.join();
} catch(InterruptedException ie) {
throw new AssertionError(ie);
}
// Other initialization
}
public static void main(String[] args) {
System.out.println(initialized);
}
}
|
Compliant Solution (static
initializer)
This compliant solution does not spawn a background thread during class initialization and uses a static
initializer.
Code Block |
---|
|
public class Lazy {
private static boolean initialized = false;
static {
// Other initialization
}
public static Initialize, for example, a database connection
initialized = true;
}
public static void main(String[] args) {
System.out.println(initialized);
}
}
|
compliant Solution (ThreadLocal
)
This compliant solution uses a ThreadLocal
object to initialize a database connection and set the initialized
flag to true
depending on whether the initialization succeeded.
Code Block |
---|
|
public class Lazy {
private static boolean initialized = false;
private static ThreadLocal<Connection> connectionHolder
= new ThreadLocal<Connection>() {
public Connection initialValue() {
try {
initialized = true;
return DriverManager.getConnection("connection-string");
} catch (SQLException e) {
initialized = false;
return null;
}
}
};
public static Connection getConnection() {
return connectionHolder.get();
}
public static void main(String[] args) {
Connection conn = getConnection();
System.out.println(initialized);
}
}
|
...