Roam
Roam

Reputation: 4949

Obtaining the lock ofan object by running its synchronized method

Running a synchronized method gives the lock of its object to the one invoking that method.

In the code of this Q, do i need to synchronize the block at all-- on object c itself or on anything else?

setInt() is a synchronized method.

In the line

c.setInt(c.getInt()+k); 

when setInt() is invoked, the lock of c is obtained since setInt() is synch'd and the lock isn't released before setInt() returns. That's the entire block and no need t synch it(?)

So,

 c.setInt(c.getInt()+k); 

would still be synchronized if i comment out "Line-A" & "Line-B" in the following code. setInt() is synchronized here, getInt() isn't:

public void update(SomeClass c) {

    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 (c) {      // Line-A                  
                    c.setInt(c.getInt()+k); 
                //    System.out.println("in "+this.toString());
            }                      // Line-B
        }  
}

This got me curious all along.

TIA

Upvotes: 0

Views: 41

Answers (1)

Tim B
Tim B

Reputation: 41178

Your question is hard to understand but I think you are asking if you are locked for the full call sequence there, the answer is that you are not. Effectively what you have put is the same as:

 int tmp = c.getInt(); // will lock and then unlock c
 tmp += k;
 c.setInt(tmp); // will lock and then unlock c.

This is why for proper thread safety you need an increment method which does both the get and set within one synchronized block.

i.e.

 c.increment(k);

Upvotes: 2

Related Questions