简体   繁体   English

Java:`静态`方法

[英]Java: `static` Methods

When I call a static method like: 当我调用静态方法时:

Something.action();

Since a instance isn't created how long will the Class of the static method be held in memory? 由于未创建实例,静态方法的Class将在内存中保存多长时间?

If I call the same method will the Class be reloaded for each call since no instance exists? 如果我调用相同的方法将为每次调用重新加载Class,因为没有实例存在?

And are only individual static methods loaded when called or are all the methods and static methods of a Class loaded into memory even though only one static method maybe used? 并且只是在调用时加载了单独的静态方法,或者将一个类的所有方法和静态方法加载到内存中,即使可能只使用一个静态方法?

Unless you have configured garbage collection of permgenspace, the class stays in memory until the vm exits. 除非您配置了permgenspace的垃圾收集,否则该类将保留在内存中,直到vm退出。 The full class is loaded with all static methods. 完整的类加载了所有静态方法。

The class stays in memory till the classloader that loaded that class stays in memory. 该类保留在内存中,直到加载该类的类加载器保留在内存中。 So, if the class is loaded from the system class loader, the class never gets unloaded as far as I know. 因此,如果从系统类加载器加载类,则据我所知,类永远不会被卸载。

If you want to unload a class, you need to: 如果要卸载类,则需要:

  1. Load the class and all the classes that refer to that class using a custom classloader 使用自定义类加载器加载类和引用该类的所有类
  2. After you are done with that class, release all references to the class - ie make sure there are no object instances of that class around 完成该类之后,释放对该类的所有引用 - 即确保该类没有对象实例
  3. Unload the class and all classes referring to it by releasing the custom classloader instance that loaded those classes. 通过释放加载这些类的自定义类加载器实例来卸载引用它的类和所有类。

In some configurations, the class is even loaded before you make the call. 在某些配置中,在您拨打电话之前,甚至会加载班级。 We used BES (Borland Enterprise Server) and we had problem with our Solaris production servers where all the referenced classes where loaded recursively at the startup of our application. 我们使用了BES(Borland Enterprise Server),我们的Solaris生产服务器出现了问题,其中所有引用的类都在我们的应用程序启动时递归加载。 That means, when the main class of our app was loaded, the app server loaded all the class referenced in the import section of that class ... recursively. 这意味着,当我们的应用程序的主类被加载时,应用程序服务器加载了该类的导入部分中引用的所有类...递归。

As a side note, unless you are running in a very memory constraint environment, or if you are loading lots and lots of unnecessary classes, you should not care too much about the memory usage of the classes loaded in memory . 作为旁注,除非您在非常大的内存约束环境中运行,或者如果要加载大量不必要的类,否则您不应过多关注内存中加载的类的内存使用情况。

The Something class should get loaded when the caller class will be loaded. 在加载调用者类时,应该加载Something类。 And it stays there until the exit of the VM as krosenvold said. 正如krosenvold所说,它一直停留在VM的出口处。

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

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