• Post Reply Bookmark Topic Watch Topic
  • New Topic

Lock - Object or Method

 
Mark Henryson
Ranch Hand
Posts: 200
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Posts: 24213
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Mark Henryson
Ranch Hand
Posts: 200
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Posts: 24213
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1170
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!