Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Synchronised instance methods in java

From some internet source

Here is a synchronized instance method:

public synchronized void add(int value){

  this.count += value;
}

Notice the use of the synchronized keyword in the method declaration. This tells Java that the method is synchronized. A synchronized instance method in Java is synchronized on the instance (object) owning the method. Thus, each instance has its synchronized methods synchronized on a different object: the owning instance. Only one thread can execute inside a synchronized instance method. If more than one instance exist, then one thread at a time can execute inside a synchronized instance method per instance. One thread per instance.

Here's my understanding. If I have a runnable object, that contains an instance of the class containing the above add method, then

Case 1 : I have two threads, each having the same instance of class containing the add method, then only one will be able to execute the above add method at a time. Hence if one thread calls add then it CAN NOT be pre empted before it finishes the execution?

Case 2 : If both my threads have two different instances of the class containing the add method, then it synchronisation does not really play any role in this case. The two of them will execute, as if synchronisation was not applied at all.

Am I correct in my understanding?


1 Answers

Yes, however

then it CAN NOT be pre empted before it finishes the execution?

A lock doesn't stop a thread being pre-empted, but it does stop any other thread from obtaining the same lock. i.e. it looks the same, even though the thread can stop for a short time while holding a lock.

as if synchronisation was not applied at all.

The difference is that without synchronized it would be much faster. As it is such a simple operation. If you were doing something less trivial, the cost of synchronization would be relatively small. In any case, correctness is more important than speed in almost all cases.

like image 195
Peter Lawrey Avatar answered Jan 24 '26 03:01

Peter Lawrey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!