Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to dynamically restart a HelloWorld Java program which loops print outputs?

Tags:

java

restart

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?

like image 807
Caffeinated Avatar asked Apr 22 '15 01:04

Caffeinated


People also ask

How do you restart a Java program by itself?

Strictly speaking, a Java program cannot restart itself since to do so it must kill the JVM in which it is running and then start it again, but once the JVM is no longer running (killed) then no action can be taken.

How do you repeat a whole program in Java?

It can be done relatively easily by moving your code out into a separate method, and then calling that method over and over again... The main() method just controls the repeating of your program. All the other questions and processing occurs in the runMyCode() method.


2 Answers

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
like image 72
M A Avatar answered Oct 20 '22 19:10

M A


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.

like image 41
Paul Avatar answered Oct 20 '22 20:10

Paul