Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I close my software in a safe way?

Up to now I used my application as a stand alone product. So, when user pressed "Stop" button I called System.exit(0); and it was fine.

Now my application will be called (in a programmatic way) from another program. So, I afraid that System.exit(0); will kill not only my process but also the external software which started my program.

So, what is the correct way to shutdown my application if a corresponding request from an external software is received? My application is an GUI application. So, I want to close the window but I also want to close all processes performed by my program.

ADDED:

To be more specific, I want to close all threads started by my program. My program does not start any OS process or any other program.

like image 334
Roman Avatar asked Nov 06 '22 14:11

Roman


1 Answers

If the threads you've launched are still processing then calling System.exit(0) will cause them to be killed. In some cases, this can leave your application in an inconsistent state. Imagine that the thread was saving a file for example.

You should ensure that the your threads are all 'happy' to die before calling System.exit.

One technique you can use for this with long running threads is poisoning. To do this you send the threads a message that they should now die gracefully - i.e. a poson message. Once they have all died, it is safe to call System.exit(0) to terminate the Swing event handling thread.

There a loads of different ways of implementing poisoning, you could just set a global flag variable that the threads check to see if they've been poisoned, or you could use the Java 5 threading libraries. Take a look at this Javadoc for example and you'll find references to this technique:

http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/BlockingQueue.html

like image 139
Steve Neal Avatar answered Nov 12 '22 13:11

Steve Neal