Java puzzle System.exit and locks.
When you call System.exit() it will stop the execution of the thread at that point and not call any finally blocks.
private static final Object lock = new Object(); public static void main(String... args) { Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { @Override public void run() { System.out.println("Locking"); synchronized (lock) { System.out.println("Locked"); } } })); synchronized (lock) { System.exit(0); } }What does this program print? Replace System.exit(0) with Thread.currentThread().stop() and run again for comparison.
Also funny is that this doesn't exit (at least not in Java 6):
ReplyDeleteRuntime.getRuntime().addShutdownHook(new Thread() {
public void run() {
System.exit(0);
}
});
System.exit(0);
Locking?
ReplyDeleteJust guessing, but I think the System's exit lock reaches earlier the object so the thread should wait for the release, but the JVM can't stop until all threads stops it work, so I think we'll see "locking" and the system doesn't exit just wait,wait,wait...
ReplyDeleteI really wonder why System.exit(..) doesn't check if it was already called (and do nothing if that's the case).
ReplyDelete