Why does the JVM sets a larger heap size when I add unused jars to the classpath

Viewed 116

I have a jvm that runs inside a cpp program using JNI and receives a CLASSPATH parameter. I saw that when I add jars to the CLASSPATH the, heap size and usage is larger even when the classes in these jars are not loaded or called in any way.

Can someone explain why this happens? is it some memory optimization the JVM trying to do?

Can I change this behavior?

1 Answers

Can someone explain why this happens?

When a classloader initializes, it will read and cache the index for each JAR file1 on its classpath. I'm not sure if this is done eagerly or lazily, but in either case you could end up with the index cached even though no classes were loaded from a given JAR . (The classloader often has to check multiple JARs to find what it is looking for.)

(Come to think of it, the JVM could be mapping the entire file into memory. I haven't checked the JVM source code to see what it actually does.)

Is it some memory optimization the JVM trying to do?

It is optimizing class and resource load times. Caching the indexes avoids the classloader having to re-read them each time the classloader loads a class or other resource.

Can I change this behavior?

Probably not.

But here's the thing. The amount of memory that you would save by doing this is relatively small. It is probably not worth worrying about.

And if you are really concerned by the amount of memory "wasted" by this, consider reorganizing the JAR files on your application's classpath so that they only contain classes and other resources that the application is actually going to use. (There are tools that can help you do this kind of thing ...)


1 - ... or ZIP file.

Related