This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
First, the fact is that it's threads that are actually running and seeking & releasing locks. Every instance in the RAM is represented by at least a thread. Then, let's take a close look at the lock issue: When the instance (or a thread) is running and is up to the time to invoke a synchronized lock, it enters the stage of lock-seeking. If seeking fails, it may try again later. If seeking succeeds, the instance (or the thread) gets the lock and run the code inside the synchronized method and release the lock upon finishing. The instance (or the thread) can't do anything else simultaneously, except for that it starts another thread. The started thread may encounter synchronized method and goes through the same necessary stages. Therefore, the question of "Whether an instance or the invoking method owns the synchronized method?" is answered by the fact that an instance (or a thread) can't do anything else when running in a invoking method of a synchronized method. Then, either of the two can be said to own the lock. However, the question of "whether an instance can have multiple locks?" boils down to a question of "whether an instance can be run in multiple threads?". In most cases, that's not the case.
" Veni, vidi, vici "<br />" I came, I saw, I conquered "
I'd just like to emphasise that any object instance has exactly one monitor lock. So if you have two synchronized methods a() and b(), only one of them can execute at any given time. - Peter
Joined: Jan 08, 2002
Laudney, You've said, However, the question of "whether an instance can have multiple locks?" boils down to a question of "whether an instance can be run in multiple threads?". In most cases, that's not the case. Refers to "most case". So, what's the exception of "most case" where an instance can be run in multiple threads?
Joined: Jan 06, 2002
Well, in fact, I haven't been informed of any exceptions. I said "most cases" just for avoiding extremism.
Each Object instance has a single lock that must be obtained by any thread executing a synchronized method of that instance. Two threads may not grab the same lock. That said, you could create multiple instances of Object as members of a parent Object. Instead of grabbing the lock (calling a synchronized method) on the parent Object, you could grab the lock of one of the member Objects. That way you could seem to have multiple locks on a single object. ...Mike B.
Peter den Haan
Joined: Apr 20, 2000
"broadbear", sorry to be a bore but could you please review our naming policy and reregister? The reason behind it is that reading JavaRanch should be a bona fide thing to do in the workplace, and keeping a professional appearance is part of that. - Peter