Email address:
Password:
SCJP/OCPJP 1.6 certification
Practice Exams and Training

Please explain in details.


The class containing this very logic without any additions is in fact THREAD SAFE!!!

There are no modifications to the fields except of the synchronized method.


How can the other instance of the class modify these variables?

Let's say we have two instances of this class called a1 and a2.


This is our sensitive method:


public synchronized void goNow(){
  x++;
  y++;
}


What the synchronized keyword of this method does it it locks down the current object in a way that another thread trying to access this method has to wait until the first thread releases the lock of the same object. That way, it would ensure only one thread would be running on this method at a time. However, that happens only if we assume there are only one object of the surrounding class.


The problem is when we have two or more objects of the class, we can no longer ensure there would be only one thread running inside this method at a time. Let's say we have a thread that tries to enter into this method on a1 object. Before entering the method, it takes the monitor lock of that a1 object. This makes another thread willing to enter into that method on a1 object has to wait.


However, we have the a2 in the unlock state. If there is another thread trying to enter into this method on a2, it can independently enter in by locking down that a2 object.


The workaround suggested in this question is to add static keyword to the method, which makes the monitor lock apply on the global class-template of this class, instead of on individual objects of it.


If you find yourself unfamiliar with the 'lock' concepts of the thread mechanism, I strongly suggest you watch our threads video to gain a better understanding of the lock mechanism.

ExamLab © 2008 - 2024