Unable to understand Class object Unable to understand Class object multithreading multithreading

Unable to understand Class object


1. When is it created?

It is created when the class is loaded by the JVM using a classloader. A class is loaded when it is referenced by some other class. A ClassLoader typically creates this Class instance when calling ClassLoader#loadClass(String className). This is explained in this link from the Java Language Specification:

Loading refers to the process of finding the binary form of a class or interface type with a particular name, perhaps by computing it on the fly, but more typically by retrieving a binary representation previously computed from source code by a Java compiler, and constructing, from that binary form, a Class object to represent the class or interface.

2. Is it Garbage Collected at some point of time?

Just like any other instance, if the Class instance is no longer reachable, it is eligible for GC. This happens when no object of the type represented by the Class instance is reachable, and the classloader that loaded the class is not reachable as well.

3. As it is used by synchronized static method, does it mean there will be only one instance of Class object per JVM?

Not necessarily. If you define a custom classloader, then you could have two instances of a Class. In this scenario, you may even get a ClassCastException if you try to convert an object that is of some class A to the "same type" A if they were loaded by two different classloaders.


  1. From the JavaDocs on Class:

Class has no public constructor. Instead Class objects are constructed automatically by the Java Virtual Machine as classes are loaded and by calls to the defineClass method in the class loader.

  1. As long as instances of a class are in use and references to the Class object persist, it will stay in memory.

  2. Yep. Class is immutable so there's no real synchronization concern there.