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" ?
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.
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.
You can use System. exit() OR break The java. lang.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With