Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does jvm load all the classes mentioned by the classpath?

When we invoke java command with -cp command then we provide some directories and jar files. Does jvm load all the classes mentioned by the classpath Or it is just a super set of all classes which jvm will look up to load when required?

like image 224
hsingh Avatar asked Jun 24 '15 12:06

hsingh


2 Answers

Does jvm load all the classes mentioned by the classpath Or it is just a super set of all classes which jvm will look up to load when required?

JVM loads classes form the classpath on the need basis i.e. when a reference is found for the class, it is loaded. Also there is a hierarchy of class loaders in JVM, a class loaded by the parent class loader is used by the lower class loaders.

like image 141
Juned Ahsan Avatar answered Sep 20 '22 10:09

Juned Ahsan


There are two concepts involved

  • loading
  • initialization

Initializing a class will initialize fields and execute static blocks. The exact moment this happens is important to application semantics, therefore it is precisely defined.

Initialization requires loading first; but loading is more of an internal concept of the JVM. JVM could, and is allowed to, aggressively preload classes even if unneeded. This process does not affect the application semantics and it is invisible to the application.

As far as the application is concerned, a class must have been loaded if we get a Classobject of it, e.g. from Foo.class, Class.forName, or other reflection APIs. We can examine the properties of the Class without necessarily triggering initialization.

One important constraint - we must get the same Class object for the same class name (and from the same classloader). The Class object is the representation of the loaded class.

like image 23
ZhongYu Avatar answered Sep 22 '22 10:09

ZhongYu