...
Code Block |
---|
|
public class Lazy {
private static int number;
private static Connection conn;
static {
Thread t = new Thread(new Runnable() {
public void run() {
// Initialize, a database connection
try {
conn = DriverManager.getConnection("connectionstring");
} catch (SQLException e) {
conn = null;
}
Lazy.this.number = 42;
}
});
t.start();
try {
t.join();
} catch(InterruptedException ie) {
throw new AssertionError(ie);
}
// Other initialization
number = 42;
}
public static Connection getConnection() {
if(conn == null) {
throw new IllegalStateException("Connection not initialized");
}
return conn;
}
public static void main(String[] args) {
System.out.println(number);
}
}
|
...
Code Block |
---|
|
public class Lazy {
private static int number;
private static Connection conn;
static {
// Initialize, a database connection
try {
conn = DriverManager.getConnection("connectionstring");
} catch (SQLException e) {
conn = null;
}
// Other initialization
number = 42;
}
// ...
}
|
Compliant Solution (ThreadLocal
)
This compliant solution uses a ThreadLocal
object to initialize a database connection and sets flag
to true
depending on whether the initialization succeeds. The number
field is initialized independently in a static initializer.
Code Block |
---|
|
public class Lazy {
private static boolean flag;
private static int number;
static {
number = 42;
}
private static final ThreadLocal<Connection> connectionHolder
= new ThreadLocal<Connection>() {
public Connection initialValue() {
try {
Connection conn = DriverManager.getConnection("connectionstring");
flag = true;
return conn;
} catch (SQLException e) {
flag = false;
return null;
}
}
};
public static Connection getConnection() {
return connectionHolder.get();
}
public static void main(String[] args) {
Connection conn = getConnection();
System.out.println(flag);
}
}
|
...