Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the Java JVM load an entire jar or ear if it only uses one class from it?

Tags:

java

class

loader

Lets pretend you have a 3 Gb jar file and your application only uses a small class within it. Does the JVM load the whole jar file into memory or does it read the Table of Contents and load only the pieces it needs? Is this behavior controllable?

like image 494
ojblass Avatar asked Jul 24 '09 06:07

ojblass


2 Answers

JVM loads only the required classes from the Jar when invoked. If application needs a class then the class and all other dependent classes will be loaded. Not sure but I suppose this is the responsibility of the class loader to locate the class from the classpath and load.

like image 197
Bhushan Bhangale Avatar answered Oct 23 '22 11:10

Bhushan Bhangale


Jar files are a form of zip files.

How these are handled is highly dependent upon JRE.

Old versions of the Sun JRE used to memory map the entire file. This would allocate logical memory, but not necessarily cause any of the data to be loaded from disk. (32-bit Windows is not generally capable of allocating 3 GB of contiguous memory, although you can do it on other OSs).

I believe the current behaviour is to memory map the central directory at the rear of the file under Windows. Under other OSs, it's just read. This is controlled by #defines in the source.

JDK7 is likely to do something else.

Classes are generally loaded lazily. Resources are reread each time. java.util.ResourceBundle caches.

like image 35
Tom Hawtin - tackline Avatar answered Oct 23 '22 12:10

Tom Hawtin - tackline