when we synchronize some static method lock is acquired on class.class
so what does class.class represents, by googling and reading through some forums i came to know its instance of java.lang.Class and for all the classes in memory there exists one instance of java.lang.Class associated with them. is it??
One can create object of that class with this and acquire lock on this, apart from that what all major functionalities does it offer which are useful in my regular java application??
any reference link is welcomed. Thanks!!
Basically, yes, although I think it’s one copy per classloader rather than in total. But as you normally have only one classloader…
The
Classinstance represents the class as a whole, as distinct from other classes, just as instances of classes are distinct from all other instances of that class. So since static methods are specific to the class (just like non-static methods are specific to the instance), it makes sense to synchronize on the class instance when calling a static method (if the method requires synchronization). Which is why that’s what the JLS says happens if you apply thesynchronizedkeyword to the method as a whole.