11

Consider the following simple code that prints "Hi world" forever:

public class WakeMeUpSomehow {

 public static void main(String[] args) {

    while (true) {
    try {
         System.out.println( " Hi world ");
         Thread.sleep(1000);                 //1000 milliseconds is one second.
    } catch(InterruptedException ex) {
         Thread.currentThread().interrupt();
    }
    }
 }
}

Here is the output:

enter image description here

Is there a way to devise an external third program , which watches this program to notice when we kill it (like with CTRL+C in command line); and then this "parent" program resumes the "Hello World" running ?

I think it might look something like this :

enter image description here

So my question is - how can I simulate code like this, which has this kind of fail-safe ability? Is there an way to do this?

thanks !

EDIT: I found a neat link here which is relevant but addresses something a little different- How can I restart a Java application?

Community
  • 1
  • 1
Caffeinated
  • 10,270
  • 37
  • 107
  • 197

8 Answers8

9

Shutdown hooks are guaranteed to run on normal shutdown events of a program, but not on all kinds of abnormal termination, such as when the JVM is killed forcibly.

One solution may be to use a batch script:

@echo off
setlocal

start /wait java WakeMeUpSomehow

if errorlevel 1 goto retry
echo Finished successfully
exit

:retry
echo retrying...
start /wait java WakeMeUpSomehow
M A
  • 65,721
  • 13
  • 123
  • 159
4

If it's as simple as this, you can simply use a shutdownhook.

Runtime.getRuntime().addShutdownHook(() -> {
    //do whatever you want to be done when closing the program here
});

Though you might encounter some problems, if you want to restart the program and use the same commandline.

Paul
  • 13,100
  • 3
  • 17
  • 34
4

first of all it is a challenging task. just try it and let me know whether it is working or not !!!!!

public class WakeMeUpSomehow {
    static class Message extends Thread {

        public void run() {
            try {

                while(true)
                {
                System.out.println("Hello World from run");

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        try {
            Runtime.getRuntime().addShutdownHook(new Message());
            while(true)
            {
            System.out.println("Hello World");
            Thread.sleep(100);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
kavi temre
  • 1,241
  • 2
  • 13
  • 21
1

You can use a shutdown hook which launches your application again. Please note the downside of this - your JVM will never stop running, until you force-kill it.

http://wrapper.tanukisoftware.com/doc/english/qna-shutdown.html

kaykay
  • 546
  • 2
  • 7
1

Without going into the reason why you would want to so such a thing :-), a "robust" way of doing this would be to execute your "parent" program or batch script in:

  1. Windows service to execute java programs as detailed in Install java program as a windows service: Alternative to JavaService?
  2. 3PP schedulers
  3. If you are on Linux, you could use the init daemons or Cron schedulers.

The above approaches even withstand computer restarts!

Community
  • 1
  • 1
KayDK
  • 134
  • 9
  • Curious , What are `3PP schedulers` ? – Caffeinated Apr 29 '15 at 19:12
  • 1
    3PP stands for 3rd Party Publishers :-) i.e Software developed by others. As an example, check http://quartz-scheduler.org/, one of the most famous schedulers for java applications – KayDK Apr 29 '15 at 19:17
1

You should checkout monit. It provides lot of utilities than just restarting a program.

For e.g.

  1. It checks if your program is consuming more memory (possibly due to memory leakage).
  2. Monitor for file changes.
  3. Restart program in case if it crashes.
  4. Script based support for customizing startup options.
CuriousMind
  • 3,015
  • 3
  • 24
  • 44
1

It sounds like you'd like to run your application as a Service ( windows ) or Daemon ( Unix ).

In Java you typically use a service wrapper for this. I use Apache Commons Daemon for this.

Commons Daemon provides ProcRun.exe on Windows for running your Java application as a service. You can even rename the executable to that of your program. On Unix you have JSvc for restarting your Java application. I write a thin generic start-up API in my main class which is called by both executables.

This is the only way I believe will do this reliably if you need to do this in production ( and not as an exercise of some sort ).

kervin
  • 11,246
  • 5
  • 38
  • 57
  • I think this is interesting . it says `but in those cases where the application is not interactive (server applications) there is currently no portable way to notify the Virtual Machine of its imminent shutdown.` - though it's still a little foggy how I'd use it. So you have created some code that restarts your own programs ? – Caffeinated May 04 '15 at 01:47
  • 1
    @Coffee Commons Daemon works by providing a small native executable that can run the JVM or host jvm.dll in its own process space. It then calls into your application at various API methods, including when it catches System Signals ( E.g. CTRL+C ). The result is an application at can run as a service (even interactively). Many production Java Server Applications use this approach. – kervin May 04 '15 at 01:59
  • How does JSvc compare to the `supervise` tool ? I looked up something called daemontools, and found this thing called `supervise' ? curious if we you knew about that – Caffeinated Jun 07 '15 at 23:50
0

In Windows the way to do this is to run your program as a service. It allows among other things the capability to start your program at system start up (with no user logged on) and to restart your program if it shuts down. The Windows Resource kits provided a program called SrvAny.exe that allows you to run any program as a service.

https://support.microsoft.com/en-us/kb/137890

JJF
  • 2,503
  • 2
  • 14
  • 27