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;
}
}
java.lang.Class
object created by JVM. So behind abstraction, its object locking and in the picture, we see Class locking.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 is my understanding so far regarding the subject. Please add on or rectify.
The only difference is that a static synchronized
locks on the class instance and a non-static synchronized
method locks on the instance.
People tell about two types of multi-threaded locking
There is object instance locks and Lock
style locks. A Lock
, confusingly, has both.
object and class
Not true as you have worked out already.
Just because people say stuff doesn't make it true. Often people say a lot of nonsense. In fact there is whole web sites devoted to non-sense about Java. :P