...
Code Block | ||
---|---|---|
| ||
public class Lazy { private static int number; private static Connection conn; static { Thread t = new Thread(new Runnable() { public void run() { // Initialize, for example, 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 } 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); } } |
The code in the static
block is responsible for initialization, and starts a background thread. The background thread attempts to assign initialize a database connection and also assigns to the field number
but needs to wait until initialization of the Lazy
class has finished.
...
This compliant solution also uses a static
initializer but for initialization and does not spawn a background thread from it.
Code Block | ||
---|---|---|
| ||
public class Lazy { private static int number; private static Connection conn; static { // Initialize, for example, a database connection this.numbertry { conn = 42DriverManager.getConnection("connectionstring"); } catch (SQLException e) { conn = null; } public static void main(String[] args) { System.out.println(number)number = 42; } // ... } |
Compliant Solution (ThreadLocal
)
...