I have an executable jar file. Once started the only way to stop it is to go to the task manager and end the javaw process. Is there a cleaner way to stop it, say with an UI which a novice user can use?
Since you control the code, you want to have something in the GUI that will allow for exiting using System.exit
. So, if you were using Swing, you could do something like:
JButton b = new JButton("Exit");
b.setActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
Another useful technique is to listen for windowClosing, which happens when the user clicks the X button on Windows (and the equivalent on other systems):
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
I usually put that in the constructor of the class that extends Frame for the application.
If you are using a JFrame, you also need to add this line:
setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
If your application does not have a GUI - for example if its a service - then you can use local network access to simulate the standard IPC (InterProcess Communication) mechanisms that the operating system normally uses to start and stop services.
A very popular implementation of that you can find in Apache's Commons Daemon project: http://commons.apache.org/daemon/
Your application will end when all non-daemon threads have ended. A way to do this, would be to make all threads but one daemons, and let the last thread be the one that awaits the signal to stop.