1

I am trying to provide a very simple "Do you wish to save this document?" dialog upon shutdown of my application.

I have used a WindowAdapter to do this. This works perfectly if the application is closed using any GUI action (clicking the CLOSE button, closing from the task bar, closing from the Task Manager using End Task).

However, when the user logs off or kills the application process, the JVM application receives a termination signal directly. It closes any AWT resources without user confirmation and without calling the WindowAdapter. Using a ShutdownHook, it is not possible to have any GUI interaction, because the AWT Event Dispatch Thread has already been stopped.

So far I have found multiple ways to work around this problem:

  • Use JNI or JNA to catch the terminate signal before it reaches the AWT subsystem.
    • Needs separate code for every operating system.
  • Use sun.misc.SignalHandler to catch the terminate signal.
    • Uses a SUN proprietary interface. Not guaranteed to work on other VM's.
  • Use SWT to catch the terminate signal before it reaches the AWT subsystem.
    • Well-maintained interface, but I hate pulling in SWT just to resolve this small problem.
  • Save the user data to a temporary file and treat the clean-up when the program is launched again.

Is there another, better way to fix this? It seems strange there is no standard way to implement something so basic and elementary. Can't I boot up the AWT subsystem again in some way?

parasietje
  • 1,529
  • 8
  • 36

2 Answers2

2

The host platform owns the JVM running your application. On Mac OS X you can use OSXAdapter, discussed here. Other systems may have a similar mechanism. One useful defensive measure is to use java.util.prefs.Preferences to record clean-up information. It's platform-independent and typical implementations offer best-effort retention for a given platform.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
1

Maybe you complicated very simple thinks, instead of terminating current JVM instance

1) hide Container(s)

2) save applications properties,

3) on Exceptions show JOptionPane with something meaningful about

4) call System.exit(0);

5) a few biggest application (with Embedded_database for storing local data) saving these processess a few seconds after Containers hidden

0) maybe help you this thread about workaround in plain vanilla Java

Community
  • 1
  • 1
mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • The situation shown is upon windows shutdown. Here, the JVM is closed by the operating system. I cannot hide containers anymore; they are already closed by the JVM shutdown. – parasietje Feb 15 '12 at 08:41
  • @parasietje my question is why is possible, why whatever event(s) killed current JVM instance, that should be to much contraproductive, simple remove that ... – mKorbel Feb 15 '12 at 08:48