Reputation: 21310
Let's say I have a class Employee and I create the object of that class as
Employee emp = new Employee();
What is the difference between the below two synchronized blocks
synchronized(emp){ } and
synchronized(Employee.class)
Upvotes: 1
Views: 235
Reputation: 24780
When you syncrhonize, you need an object to define as the semaphore. When thread A is inside a syncrhonized block defined by object A, no other thread can be in other such a block defined by the object A, but it can be inside any other synchronized block defined by other objects.
emp
and Employee.class
are distinct objects, so the two synchronized blocks are not incompatible (you can have a thread inside the first and another inside the second).
In a more general note, you should use the first block to protect sensitive code that only affects to the individual employee objects, and the second one in operations where changing one employee may affect other employee critical section or a collection/aggregate value of them.
Upvotes: 1
Reputation: 5710
The first one synchronizes on specific instances of the class. So if you have 2 threads operating on two different instances of the class, they can both enter the block at the same time - within their own contexts, of course.
The second block synchronizes on the class itself. So even if you have 2 threads with two different instances, the block will be entered by only one thread at a time.
Upvotes: 1
Reputation: 691635
The first one uses one Employee instance as monitor. The second one uses the Employee class as monitor.
If the goal is to guard instance variables of an employee, the first one is makes much more sense than the second one. If the goal is to guard static variables of the Employee class, the second one makes sense, but not the first one.
Upvotes: 8