Originally posted by Someswara Chittlella:
How to specify that MethodA can be called only when it owns lock on that object with external synchronization block?
To enforce it? You can't... It must be cooperative. You can grab the lock of classA before calling a method of classA like this:
Unfortunately, you can't enforce that it *must* be grabbed prior to calling methodA(). If someone else writes code that simply call MethodA(), it will just work in parallel... To do that you have a couple of options.
- You can declare the method as synchronized (or use a synchronize block in the method) -- so it will definitely grab the lock.
- With
Java 5, you can actually check to see if the lock is held with the Thread.holdsLock() method.
Henry