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.

Comments

  1. Also funny is that this doesn't exit (at least not in Java 6):

    Runtime.getRuntime().addShutdownHook(new Thread() {
    public void run() {
    System.exit(0);
    }
    });
    System.exit(0);

    ReplyDelete
  2. Just 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...

    ReplyDelete
  3. I really wonder why System.exit(..) doesn't check if it was already called (and do nothing if that's the case).

    ReplyDelete

Post a Comment

Popular posts from this blog

Low Latency Microservices, A Retrospective

Unusual Java: StackTrace Extends Throwable

System wide unique nanosecond timestamps