Reputation: 4697
Let's assume an application with a dependency. The dependency comes in form of a jar file. The dependency jar file contains many classes. The application uses only one class from the dependency jar.
Do the unused classes included in the dependency jar lead to higher memory consumption, even if they are not used (directly and indirectly) by the application.
I guess it's a question of the classloader implementation, but do classloaders really behave differently in this question? I think it would be enough to answer this question for the default JRE / JDK classloaders and maybe classloaders of common containers and application servers.
Does the classloaders load the entire jar file? And is it just temporary to load the needed classes and after that the jar file is removed from memory? Or are all classes loaded, even the unused ones?
When I organize my projects, I tend to split the classes etc. in many small projects. I don't do this to save disk space, because disk space is relatively cheap. I do this because it increases reusability. I don't have much fear of the "dependency hell" even if the number of small projects gets pretty high. I use dependency- / build-tools to automatically resolve the dependencies for me.
So there is the diskspace aspect and the code / resuability aspect of project organization. The third aspect of project organization is the runtime / classloader aspect which I'd like to be answered. While applications rarely run out of disk space, the shortage of memory is a realistic scenario, depending on the enviroment.
Upvotes: 2
Views: 2338
Reputation: 1489
The short answer is YES
. Memory consumption is higher.
The classloader does not load the entire JAR file. Through a ZipFile object, it only keeps a list of classes and an offset on where they can be found in the JAR file. If the JAR file has a lot of classes, this list is bigger, so it consumes more memory.
This memory consumption is not related to the JAR file's size itself but to the number of classes inside.
Besides this, only loaded classes use memory.
Upvotes: 3
Reputation: 3246
Memory consumption will be higher due to sheer size of jars that need to be opened and processed. But as for the classes - no, in general classes are loaded "on demand", apart from perhaps a handful from the bootstrap classpath. It does depend on the classloader implementation indeed, though.
As for cleanup of unused classes... yes, the JVM does that, in a manner similar to ordinary, reachability-based garbage collection. Be wary of classloader leaks though - sometimes the class object remains reachable in a not-at-all-obvious way, which manifests itself especially nasty in containers, and easily leads to te dreaded OutOfMemoryException: PermGen space
exceptions.
Upvotes: 1