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
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.
"I'm not back." - Bill Harding, Twister
Joined: Oct 29, 2002
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!!!
Joined: Jan 30, 2000
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.