1

I have been trying to figure out how to make a regular java application reopen on close, or simply make it not be able to close. I realize this is possible with a swing application by using DO_NOTHING_ON_CLOSE but my application does not use swing.

Say I have the following program running:

public static void main(String[] args) {
    new MyThread();
}

And MyThread runs constantly.

Say the user closes the program, is there anyway to detect that a java program is being closed and reopen it, or even better is it possible to make it DO_NOTHING_ON_CLOSE without swing?

Raedwald
  • 46,613
  • 43
  • 151
  • 237
Hugh Macdonald
  • 143
  • 1
  • 12

2 Answers2

0

If you truly want to restart the application, see this:

How can I restart a Java application?

But from your question it looks to me that you want to prevent the user to close the application. You can't prevent that, even if you do nothing when the user clicks on the X close icon or presses ALT+F4, the user will still be able to kill your application from the Task Manager for example.

icza
  • 389,944
  • 63
  • 907
  • 827
  • I realize this but is it possible to maybe create a second process within the task manager and when one or the other is killed it reopens it? – Hugh Macdonald Sep 10 '14 at 08:18
  • 2
    The Op wants to restart the application in context that when a user closes the application, it is detected and restarted or prevent closing at all (without swing). The link to the question you gave just provides a method to restart without info on how to detect closing of an application. Although I am not expert on this but there is a concept of [Shutdown hook](http://docs.oracle.com/javase/6/docs/api/java/lang/Runtime.html#addShutdownHook%28java.lang.Thread%29) , which might help in detecting closing of application. – Mustafa sabir Sep 10 '14 at 08:20
  • In my answer I wrote that you can't prevent an application from being closed. ShutDown hooks can be used to run some code before the application is closed but not to prevent it being closed. – icza Sep 10 '14 at 08:24
  • Shutdown hook won't work for Ctrl-C (`kill -9`) anyways. – mostruash Sep 10 '14 at 08:54
0

Something like this is common for daemon programs. But in general it can not be done because it must be possible to shutdown a misbehaving program.

What you can do is to have a second, watchdog program, which detects if you program has exited, and if so, restarts your program. But if the watchdog is killed, your program will stay dead.

Raedwald
  • 46,613
  • 43
  • 151
  • 237
  • I already had an idea of doing this, I edited the OP, I just need an example on how to create this second 'watchdog' process. Thanks :) – Hugh Macdonald Sep 10 '14 at 08:55