Java Reference
In-Depth Information
private static boolean initialized = false;
private static Thread t = new Thread(new Runnable() {
public void run() {
initialized = true;
}
});
static {
t.start();
}
public static void main(String[] args) {
try {
t.join();
} catch (InterruptedException e) {
throw new AssertionError(e);
}
System.out.println(initialized);
}
}
Although this does eliminate the deadlock, it is a very bad idea. The main thread waits for the
background thread to finish its work, but other threads don't have to. They can use the class Lazy as
soon as the main thread has finished initializing it, allowing them to observe initialized when its
value is still false .
In summary, waiting for a background thread during class initialization is likely to result in
deadlock. Keep class initialization sequences as simple as possible. Automatic class initialization is
known to be a very difficult language design problem, and Java's designers did a fine job in this
area. Still, there are many ways to shoot yourself in the foot if you write complex class initialization
code.
 
 
Search WWH ::




Custom Search