Roam
Roam

Reputation: 4949

Synchronizing on a lock object vs on the object processed

In the code of this Q,

if I synchronize the block on some lock object instead of the object c itself, the code is executing almost twice faster with, from what i see, accurate results. Everything else in the code is the same:

public void update(SomeClass c) {

Object lock = new Object();
    while (<condition-1>) // the conditions here and the calculation of 
                               // k below dont have anything to do 
                               // with the members of c
        if (<condition-2>) {
            // calculate k here 
            synchronized (lock) {                        
                    c.setInt(c.getInt()+k); 
                //    System.out.println("in "+this.toString());
            }
        }  
}  

Why is that so?

TIA

//=============================

EDIT:

With this lock above, the threads are running one after the other-- one thread is running the whole sequence, then another taking over the and running until all seq.is done & so forth. that's how i'm getting the accurate result. why is this happening w/this lock?

Upvotes: 1

Views: 53

Answers (1)

omu_negru
omu_negru

Reputation: 4770

If you are calling the update method from multiple threads (with the same SomeClass reference) and lock on c, then all of the threads will stand in line waiting for the lock to the c object.

If you instead lock on the lock object, a new one will get created on each method call , and each thread will synchronize on it's own lock (probably not what you intend), thus speeding the execution

Upvotes: 1

Related Questions