views:

998

answers:

4

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?

+11  A: 

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.

krosenvold
This is not strictly true, though it is a reasonable mental model of class loading.Some VMs will dynamically unload unused classes in order to reduce the resident memory size; however, such an optimization will only come into play with very long running processes and only on VMs that implement it.
Aaron Maenpaa
+4  A: 

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.
Gowri
+1  A: 

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.

boutta
+2  A: 

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 .

Guillaume
What were some of the problems you had with the referenced classes being loaded "prematurely"? I'm curious what kind of issue that would case.
matt b
The issue was that we had the same libraries running on the server and on the client. Some of the code path would not be taken on the server, so we tried to remove unnecessary libraries that would not be called. Even if the code wasnt called, the app would crash at startup.
Guillaume