Oracle Java documentation on Intrinsic Locks and Synchronization says:
You might wonder what happens when a static synchronized method is invoked, since a static method is associated with a class, not an object. In this case, the thread acquires the intrinsic lock for the Class object associated with the class. Thus access to class's static fields is controlled by a lock that's distinct from the lock for any instance of the class.
I did not completely understand the concept of Class object
. After studding some online content I get to know:
A Class object is sort of a meta object describing the class of an object such as name, package etc.
My questions are:
There is a similar question what is Class Object(java.lang.class) in java. But it doesn't answer my questions.
[Update]
A new question is added in the comment section of the answer provided by manouti
as he mentioned there can be multiple instance of Class
object:
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.
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.
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.
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.
As long as instances of a class are in use and references to the Class object persist, it will stay in memory.
Yep. Class is immutable so there's no real synchronization concern there.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With