Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do Java classes have an instance on machine (JVM) level if they contain only static methods and fields?

Do Java classes have an instance on machine (JVM) level if they contain only static methods and fields?

And if yes, what are the effects of static methods and fields when doing multithreading? Any rules of thumb?

like image 390
Marcus Avatar asked Feb 10 '26 18:02

Marcus


1 Answers

Yes, for each loaded class in the JVM there is an instance of java.lang.Class. It does not matter whether they only contain static methods/fields or instance methods/fields as well.

And this does not have any extra impact on multi-threading beyond what instance fields and methods already have. That is, as long as you realise that the value of a static field is shared between all instances. If you want to synchronize, you need to synchronize on the java.lang.Class instance for the class (or if the method is a static method inside said class, it can have the 'synchronized' modifier on the static method to have the same effect as synchronizing on the java.lang.Class instance for the class).

One extra thing to note is that a class with the same name can be loaded by more than one classloader at the same time in the JVM- hence classes in Java are not uniquely identifier by their fully-qualified name, instead they are uniquely identifier by the combination of java.lang.ClassLoader instance used to load the class, and the fully-qualified name.

like image 93
Erwin Bolwidt Avatar answered Feb 15 '26 11:02

Erwin Bolwidt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!