If I make a method static then the thread executing that method would acquire class level lock , now if another thread tries to access some other method of the same class, would it have to wait until the first thread releases the lock on class.
So my question is : Does a class level lock lock the entire class ?
A class level object just locks the associated class object shared effectively (by association) between the instances, each object has its own lock. Locking on the class object is still just locking on an object is not really that magical when you get your head round it.
"Eagles may soar but weasels don't get sucked into jet engines" SCJP 1.6, SCWCD 1.4, SCJD 1.5,SCBCD 5
Object level locking is mechanism when you want to synchronize a non-static method or non-static code block such that only one thread will be able to execute the code block on given instance of the class. This should always be done to make instance level data thread safe. This can be done as below :
Class level locking:
Class level locking prevents multiple threads to enter in synchronized block in any of all available instances on runtime. This means if in runtime there are 100 instances of DemoClass, then only one thread will be able to execute demoMethod() in any one of instance at a time, and all other instances will be locked for other threads. This should always be done to make static data thread safe.