简体   繁体   中英

For an auto scheduled app in Java, which way is better?

I asked a question at : Any practical difference in the use of Java's static method main?

But didn't quite get the answer, so I want to put it another way, see if the question is more clear this time :

I have a class A with a static main method :

public class Class_A
{
  ...

  public static void main(String[] args) 
  {
   ...
  }
}

I also have a class B that runs non-stop 24 hours a day in the background and on every hour, it would start Class_A automatically. Class_A uses a lot of memory and is quite huge in size, so when it's finished, I hope all the memories are recycled, I'm doing my part to make sure that happens, but sometimes somewhere in the program there might be a memory leak, so would it be better for Class_B to call :

new Class_A().main(new String[]{});

So it's memory will be better recycled after it's finished ? Or is it better to call : Class_A.main(new String[]{}) ?

That's not going to help. The JVM will hold on to memory even if you remove all Class instances and call the garbage collector. the simple way around this it to use a second JVM instance. or just put the calling part in cron or something.

new Class_A().main(new String[]{});

is actually

{    // a scope for the new object
     Class_A immediatelyFreeForGC = new Class_A();
}
Class_A.main(new String[]{});

The object you created is not changing anything (unless it's constructor has side effects) because static methods are always called statically regardless of how you write it.

You can even do

 Class_A classA = null;
 classA.main();

There will be no NullPointerException because the object referenced by classA is completely ignored.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM