Supriya
Supriya

Reputation: 21

What are the situations does the JVM decide Eager loading on a class?

what is the difference between lazy loading and eager loading. Under what circumstances does lazy loading and eager loading happens.

Upvotes: 2

Views: 713

Answers (2)

jreznot
jreznot

Reputation: 2774

One more possible reason of eager class loading in JVM is class verifier in examples like this:

class Demo {

  public HoneyApi getApi() {
    return new HoneyImp();
  }

Here HoneyImpl definition will be loaded by verifier on Demo class loading in order to check that classes are compatible to not perform that check on every call.

You may try to run JVM with -noverify to exclude verifier and see that HoneyImpl is not loaded on Demo class loading anymore.

See also JVM LS 12.3.1 https://docs.oracle.com/javase/specs/jls/se7/html/jls-12.html#jls-12.3.1

Upvotes: 0

Thiru
Thiru

Reputation: 11

The JVM must be able to load JVM class files. The JVM class loader loads referenced JVM classes that have not already been linked to the runtime system. Classes are loaded implicitly because: • The initial class file - the class file containing the public static void main(String args[]) method - must be loaded at startup. • Depending on the class policy adopted by the JVM, classes referenced by this initial class can be loaded in either a lazy or eager manner.

An eager class loader loads all the classes comprising the application code at startup. Lazy class loaders wait until the first active use of a class before loading and linking its class file.

The first active use of a class occurs when one of the following occurs: • An instance of that class is created • An instance of one of its subclasses is initialized • One of its static fields is initialized

Certain classes, such as ClassNotFoundException, are loaded implicitly by the JVM to support execution. You may also load classes explicitly using the java.lang.Class.forName() method in the Java API, or through the creation of a user class loader.

Based on the above rules, lazy class loading can be forced on the system.

Upvotes: 1

Related Questions