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

Locks

 
josephine chen
Ranch Hand
Posts: 216
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
These are the answers given
but i did'nt understand them
can anyone explain??
Locking is the main mechanism for restricting simultaneous thread access to specific java code. Which of the following statement(s) are true regarding locks / monitors?
a)One lock / monitor is associated with each Class
b)One lock / monitor is associated with each Synchronized block
c)One lock / monitor is associated with each Thread
d)One lock / monitor is associated with each Object
e)All of the above
a,b,d
 
Tony Alicea
Desperado
Sheriff
Posts: 3226
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I understand that objects and classes have locks, not code blocks nor methods. When a synched method is executed, the lock for the object has to be obtained first.



For <CODE>static</CODE> synched methods, the lock for the class is grabbed instead.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
All are true, I think, whether the test writer realized it or not.
C is misleading - every Object has a lock, and all Threads are Objects, therefore every Thread has a lock. But no do all other objects, so that's not very informative. But it's still true.
As for B, every synchronized code block seeks the lock of the monitor object or class named in the synchronized statement, or with the current instance or class if none is named. Thus the synchronized block is also "associated" with a lock, but in a different way than the monitor is. But the language is vague, so this is valid.
 
josephine chen
Ranch Hand
Posts: 216
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How do u Obtain alock on any object?
Is it when i call a synchmethod thru the object that the
object gets the lock
It is not clear!!!
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes. If a code block says "synchronized (someObject)", then the JVM will obtain a lock on someObject. If the code block does not name an object, or if "synchronized" is part of a non-static method declaration, then the JVM gets a lock on "this", the current instance of the enclosing class. If a static method is synchronized, then the JVM obtains a lock on the enclosing class.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic