devxlogo

Java Virtual Machine Doesn’t Exit

Java Virtual Machine Doesn’t Exit

You may have been surprised and frustrated to find that in some cases, the Java Virtual Machine (JVM) does not stop running when your application exits the static main() method. For example:

 public class FrameTest extends java.awt.Frame {	public static void main(String[] args) {		FrameTest ft = new FrameTest();		ft.setVisible(true);		ft.setVisible(false);		ft.dispose();		ft = null;	}  //  public static void main()}  //  public class FrameTest extends java.awt.Frame

When this code is run as an application, the JVM will not exit. However, it will exit if you delete the calls to setVisible() and run it again. The reason for this change in behavior is that making the Frame visible activates the event thread, which is responsible for calling event handler methods and for painting. Once the event thread is running, the JVM doesn’t exit because the event thread is not a daemon thread, and the JVM only exits when no daemon threads are running. To force the JVM to exit, you should call the System.exit() method, which takes a single integer value as a parameter. For example:

 public class FrameTest extends java.awt.Frame {	public static void main(String[] args) {		FrameTest ft = new FrameTest();		ft.setVisible(true);		ft.setVisible(false);		ft.dispose();		ft = null;		System.exit(0);	}  //  public static void main()}  //  public class FrameTest extends java.awt.Frame
See also  11 Effective Keyword Research Tools and Techniques
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist