This week's book giveaway is in the General Computing forum.
We're giving away four copies of Arduino in Action and have Martin Evans, Joshua Noble, and Jordan Hochenbaum on-line!
See this thread for details.
The moose likes Threads and Synchronization and the fly likes Lock - Object or Method Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Java » Threads and Synchronization
Reply Bookmark "Lock - Object or Method" Watch "Lock - Object or Method" New topic
Author

Lock - Object or Method

Mark Henryson
Ranch Hand

Joined: Jul 11, 2005
Posts: 200
Hi,

I have a small doubt in Thread. Whether lock is for methods or objects.
For example:
I am having a object 'a' which has three methods 'method1()' and 'method2()' and method3().
Of which, mehtod1() and method2() are synchronized.

Object a:
---------
synchronized method1(){}
synchronized method2(){}
method3(){}

Whether a thread by name 't1' now acquiring lock on Object a or method1()?

If a thread 't1' is holding the lock of method1(), is it possible for some other thread 't2' to acquire lock on method2() of same object 'a'.

Please clarify my doubts and also give your tips regd this.

Note: Based upon the answer from the group, I have one more question to ask.
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24081
    
  15

The lock is per-object, not per-method. Each object has a single lock associated with it.

I'm going to move this to our "Threads and Synchronization" forum for followup.


[Jess in Action][AskingGoodQuestions]
Mark Henryson
Ranch Hand

Joined: Jul 11, 2005
Posts: 200
If the lock is per object means, suppose a object have 10 methodsand only one methos is synchronised. When a thread wants to do some operation with that synchronized method, it's acquiring the lock on that object.

But the other thread wants to access the remaining 9 methods, so it will wait. Is there any possibilities to avoid this?
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24081
    
  15

No, the second thread won't wait. A thread must lock the object to enter a synchronized method; it doesn't need the lock to enter an unsynchronized method. The second thread will proceed with no interference.

That's the entire meaning of synchronized as applied to an instance method: "wait until you can lock this object before proceeding." Without that keyword, the lock is ignored.
Mr. C Lamont Gilbert
Ranch Hand

Joined: Oct 05, 2001
Posts: 1170

There is a key and a locked area. The locked area is either a whole method or a block of code. The key is whatever object was used.

The key is better referred to as a monitor.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Lock - Object or Method
 
Similar Threads
Some Thread Synchornization questions ?
locks threads
Reg : Synchronization access
Synchronizing Static Methods
synchronized keyword use