Restart Java-Application from the inside (without searching the current path and execute it)

StackOverflow https://stackoverflow.com/questions/22994366

  •  01-07-2023
  •  | 
  •  

문제

I have code like this:

public static void main(String[] args) {
  try {
    Application.start();
  } catch (Exception e) {
    try {
        Thread.sleep(2000);
    }catch (Exception i){}
    main(args);
  }
}

If the program fails, main will be called again in the "catch"-section. This is really ugly I know.

My biggest problem is the fact, that each call of main will generate a new instance on the stack, which prevents the old instance to get inactive (and garbage collected).

Is there a way to do this?

EDIT: The goal is, that if the application gets an error while it is running, it should COMPLETELY restart. The error can appear when the program is running, not before it starts to run.

The RAM takes more and more space, the more main() is newly called (=the more exceptions appear).

Application.start() should only be called, if there appears an exception. I tried to visualize it with a cheapy paint drawing. :)

enter image description here

도움이 되었습니까?

해결책

I agree you should avoid recursion here. Why not just move the Thread.sleep out of the catch block and use a boolean flag that is only set to true if things work OK.

public static void main(String[] args) {
  boolean ok = false;
  while (!ok) {
    try {
      Application.start();
      ok = true;
    } catch (Exception e) {
      // error message
    }
}

다른 팁

Why not change main to something like: -

while(true) {
  try {
    Application.start();
  } catch (Exception e) {
    try {
        Thread.sleep(2000);
    } catch (Exception ignored) {}
  }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top