Over a million developers have joined DZone.

Java puzzle System.exit and locks

· Java Zone

Learn more about the advantages of moving from a monolithic to microservices architecture.  Brought to you in partnership with IBM.

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() {
        public void run() {
            synchronized (lock) {
    synchronized (lock) {
What does this program print?

Replace System.exit(0) with Thread.currentThread().stop() and run again for comparison.


From http://vanillajava.blogspot.com/2011/12/java-puzzle-systemexit-and-locks.html

From Idea to Application gives you the architecture to quickly build, manage and run a range of applications (web, mobile, big data, new smart devices, etc.) on an open-standard, cloud-based platform. See why developers are using IBM Bluemix. Brought to you in partnership with IBM.


The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}