tags:

views:

500

answers:

4

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?

+3  A: 

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.

Bhushan
A: 

The default class loader only loads what it needs, when it needs it. If you have a 10MB JAR in your CLASSPATH, and only one .class file is needed, the JVM will only load that class the first time your code tries to access it. The .class bytecode goes into the perm space.

It's "controllable" in the sense that you can write your own class loader, but it takes some expertise to do so.

duffymo
A: 

Hi,

It entirely depends upon JVM and classloader. JVM spec specifies class should appear to be loaded on its first active use. Class loaders can load some of the classes earlier than required in anticipation. In reality most of class loaders delay loading as long as possible.

prasadvk
+1  A: 

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.

Tom Hawtin - tackline