Avoid JVM Exit

ID

java.avoid_jvm_exit

Severity

high

Resource

Api

Language

Java

Tags

CWE:382, NIST.SP.800-53, PCI-DSS:6.5.6

Description

Improper use of JVM exit within a J2EE application.

Rationale

Using System.exit() in Java applications results in the immediate shutdown of the JVM, which can lead to unclean termination of processes, resource leaks, and unfulfilled shutdown hooks. It bypasses the normal application lifecycle management, causing critical processes and resources to be abruptly stopped.

This practice is particularly problematic in server or multithreaded environments where unexpectedly ending the application can cause loss of data and lead to system instability.

Consider the following code snippet that improperly uses System.exit():

public class Application {

    public static void main(String[] args) {
        if (args.length == 0) {
            System.err.println("No arguments provided. Exiting application.");
            System.exit(1);
        }
        System.out.println("Application is running.");
    }
}

This code exits the JVM if no arguments are provided, which might be unnecessary and can lead to unexpected termination.

Remediation

Instead of using System.exit(), applications should employ graceful shutdown mechanisms that allow resources to be released properly and threads to complete their execution before terminating the application. Exception handling, logging, and exit status codes can be used to handle application flow more effectively without abruptly halting the JVM.

Here’s an improved version of the previous code that avoids System.exit():

public class Application {

    public static void main(String[] args) {
        if (args.length == 0) {
            System.err.println("No arguments provided. Application will not proceed.");
            return; // Exit method without terminating JVM
        }
        System.out.println("Application is running.");

        // Additional code for graceful shutdown if needed
    }
}