Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly shutdown a java command line program

Tags:

java

findbugs

I have an interactive java program that allow user to send messages to a server, which behaves kind of like a shell, accepting user's keyboard input and perform various action.

For example

myProgram> send "Login as James" to server

My program will parse the user input and perform the action, in this case, it will send the message "Login as James" to the server.

One of the command that I support its "quit", which will close all the server connection, clean up resources and shutdown the app. and the code for handling this quit command is

private void shutdown()
{
  closeAllConnection();
  cleanup();
  System.out.println("Thank you for using the tool, have a nice day!");
  System.exit(0);
}

When I run findbug against my code, a DM_EXIT bug is raised

Bug: new myProgram.messagingTools.main(String[]) invokes System.exit(...), which shuts down the entire virtual machine
Pattern id: DM_EXIT, type: Dm, category: BAD_PRACTICE


Invoking System.exit shuts down the entire Java virtual machine. This should only been done when it is appropriate. Such calls make it hard or impossible for your code to be invoked by other code. Consider throwing a RuntimeException instead.

and it complains that System.exit should not be used to shutdown the program.

Anyone have suggestion on how should I "Shutdown the application when my program receive the 'quit' command" ?

like image 736
Ferdinand Chan Avatar asked Mar 19 '13 03:03

Ferdinand Chan


People also ask

How do you close a Java program in terminal?

To end a Java program, we can use the exit() method of the System class. It is the most popular way to end a program in Java. System. exit() terminates the Java Virtual Machine(JVM) that exits the current program that we are running.

How do you stop a Java application gracefully?

In your application implement a shutdown hook. When you want to shut down your JVM gracefully, install a Java Agent that calls System. exit() using the Attach API.

How do you stop an infinite loop in Java terminal?

You can use System. exit() OR break The java. lang.


1 Answers

You're fine. The warning says "This should only been done when it is appropriate" (emphasis mine)

This is an appropriate way to use System.exit so you can ignore the warning.

Alternatively, if your entire program is run from main without spawning any new threads then you can just return from main and let the program shut down by itself. If you have any new threads (especially if you're using Swing) then you're probably better off just using System.exit...unless those threads also need to do some cleanup, in which case you'll need a way to shut them all down gracefully.

like image 140
Cameron Skinner Avatar answered Sep 28 '22 15:09

Cameron Skinner