If I call non-synchronized method from another class with lock on that original object(using synchronized block) can any other thread can access the method of the original object? For e.g I have a class called ClassA and all methods in that class are not synchronized. If I call a method MethodA from ClassB object with lock on object of ClassA. Then, can any other thread access methodA?
For e.g I have a class called ClassA and all methods in that class are not synchronized. If I call a method MethodA from ClassB object with lock on object of ClassA. Then, can any other thread access methodA?
Depends on how MethodA is called. If another thread simply calls MethodA, then yes, another thread can access methodA, concurrently. If there is a requirement that methodA can only be called when you own the lock of ClassA -- with an external synchronized block -- then only one cooperating thread will be able to access methodA at a time.
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.