People tell about two types of multi-threaded locking - object and class. In my knowledge, locking is done on objects only.
Case 1: On objects we create using new
or factory methods etc.
void synchronized myMethod(Type param) {
//will lock on the instance used to call this method
}
or
synchronized(this) {
//will lock on current object
}
or
synchronized(obj1) {
//will lock on specified obj1 object
}
Case 2: On java.lang.Class
objects
This is called class lock, and can be used with static fields or methods or blocks, as they belong to class and shared among all the objects, and other class properties.
static void synchronized method() {
//will lock the Class object
}
or
static {
synchronized(SomeClass.class){
int a = 2;
}
}
- Why I am thinking this also as an object locking because classes are loaded into the Method Area in the JVM, and all the static properties of the class are wrapped inside a
java.lang.Class
object created by JVM. So behind abstraction, its object locking and in the picture, we see Class locking. - So I can also infer one more thing. Just as objects locked by a thread can not be acquired by another thread as long as it is not released by first thread, class locking (the
java.lang.Class
instance) also works in same manner. I want to know in case of synchronized static methods, lock on which class is acquired by the thread in following two cases:
- This method is called from same class where it is defined.
- This method is called from derived class with derived class name.
This is my understanding so far regarding the subject. Please add on or rectify.