...
Code Block |
---|
|
public class Lazy {
private static volatile 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);
}
}
|
...
Code Block |
---|
|
public class Lazy {
private static volatile boolean initialized = false;
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 volatile boolean initialized = false;
private static ThreadLocal<Connection> connectionHolder
= new ThreadLocal<Connection>() {
public Connection initialValue() {
try {
Connection conn = DriverManager.getConnection("connectionstring");
initialized = true;
return DriverManager.getConnection("connection-string")conn;
} 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);
}
}
|
...