Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

monitor

 
R K Singh
Ranch Hand
Posts: 5384
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
when we acquire a monitor on a block of code i.e
<code size=2>
Synchronized(someObject){
block of code
}
</code>
then no thread can execute that block of code if already that block has acquired lock on the monitor.
Que is this : is it true for same object or no object of the class can execute that block of code if already in monitor.
Thanks in Adv.
 
Arathi Rajashekar
Ranch Hand
Posts: 112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ravish,
I think this helps
void a(){
synchronized(someObjectRef) {
}
}
Here you are obtaining the some other object ref.d by someObjectRef and NOT the lock of the current object (this). Note the difference. So other threads execute sync/non_sync methods of this current object(this).THis also means other threads can't access the sync method of the someObejctRef object since the lock is held here in this thread. Here also any other thread can run any sync/non_sync method of ANOTHER object of the 'someOtherObjectRef's class. Here Because you are obtainig ONLY the object level lock and NOT class LEVEL lock.
 
R K Singh
Ranch Hand
Posts: 5384
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks ..
now two more ..
1. if a objectRef is static and I take monitor on that objectRef in someMethod, then will that lock be on *class*
2. And if a lock is on class.. does it mean that NO object of that class can execute synh methods.
TIA
 
Jose Botella
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

1. if a objectRef is static and I take monitor on that objectRef in someMethod, then will that lock be on *class*
2. And if a lock is on class.. does it mean that NO object of that class can execute synh methods.

1) Not at all. The lock of a class named MyClass is caugth when a thread is executing some of the static methods of the class MyClass. The ones that were declared with the synchonized keyword.
2) The two parts of the sentence are not related.
The point is that if a lock is obtained by a thread, not other thread can execute code protected by the same lock. In the second part of the sentence, "object of that class" is not important here. But what it's important and not said, it is what lock protects the synch methods. Because they could have been synchronized with another lock.
[ January 17, 2002: Message edited by: Jose Botella ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic