简体   繁体   English

对于Java中的自动预定应用程序,哪种方法更好?

[英]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? 我在以下位置问了一个问题: 使用Java的静态方法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 : 我有一个带有静态main方法的A类:

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. 我还有一个B类,它每天在后台24小时不间断运行,并且每小时都会自动启动Class_A。 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 : Class_A使用大量内存,并且容量很大,因此,当完成时,我希望所有内存都可以回收,我正在尽自己最大的努力来确保这种情况发生,但是有时在程序中的某处可能会发生内存泄漏,所以最好让Class_B调用:

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[]{}) ? 还是最好打电话: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. 即使您删除所有Class实例并调用垃圾收集器,JVM也会保留在内存中。 the simple way around this it to use a second JVM instance. 解决这个问题的简单方法是使用第二个JVM实例。 or just put the calling part in cron or something. 或者只是将调用部分放在cron之类的东西中。

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. 将没有NullPointerException因为classA引用的对象被完全忽略。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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