简体   繁体   中英

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?

If I call the same method will the Class be reloaded for each call since no instance exists?

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. 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. 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. And it stays there until the exit of the VM as krosenvold said.

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