Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Java puzzle System.exit and locks

DZone's Guide to

Java puzzle System.exit and locks

· Java Zone
Free Resource

Microservices! They are everywhere, or at least, the term is. When should you use a microservice architecture? What factors should be considered when making that decision? Do the benefits outweigh the costs? Why is everyone so excited about them, anyway?  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() {
        @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.

 

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

Discover how the Watson team is further developing SDKs in Java, Node.js, Python, iOS, and Android to access these services and make programming easy. Brought to you in partnership with IBM.

Topics:

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
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.
Subscribe

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

{{ parent.tldr }}

{{ parent.urlSource.name }}