Java – unable to understand class objects

The Oracle Java documentation on internal locks and synchronization says:

I don't fully understand the concept of class objects After learning about some online content, I learned that:

My question is:

>When will it be created? > Do you collect garbage at certain times? > Since it is used by the synchronized static method, does it mean that each JVM has only one instance of a class object?

There is a similar problem. What is class object (Java. Lang. class) in Java But it didn't answer my question

[update]

A new question was added in the comments section of the answer provided by manouti because he mentioned that there can be multiple class object instances:

>If there are multiple class object instances, is it possible for multiple threads to access static synchronization methods at the same time?

Solution

1. When will it be created?

It is created when the JVM loads classes using the class loader When a class is referenced by another class, the class is loaded Classloader usually creates this class instance when calling classloader #loadclass (string classname) This will be explained in this link from the Java language specification:

2. Do you collect garbage at some time?

Like any other instance, a class instance qualifies for GC if it is no longer accessible This happens when no object of the type represented by the class instance can be accessed, and the class loader that loads the class is also inaccessible

3. Since it is used by the synchronized static method, does it mean that each JVM has only one class object instance?

unnecessary. If you define a custom class loader, you can have two instances of a class In this case, if you try to convert an object of class A to "same type" a (if they are loaded by two different class loaders), you may even get ClassCastException

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>