| Author |
Doubt in Threads
|
Someswara Chittlella
Greenhorn
Joined: Jul 09, 2006
Posts: 3
|
|
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?
|
 |
Henry Wong
author
Sheriff
Joined: Sep 28, 2004
Posts: 16681
|
|
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. Henry
|
Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
|
 |
Someswara Chittlella
Greenhorn
Joined: Jul 09, 2006
Posts: 3
|
|
How to specify that MethodA can be called only when it owns lock on that object with external synchronization block?
If there is a requirement that methodA can only be called when you own the lock of ClassA
|
 |
Henry Wong
author
Sheriff
Joined: Sep 28, 2004
Posts: 16681
|
|
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
|
 |
Henry Wong
author
Sheriff
Joined: Sep 28, 2004
Posts: 16681
|
|
Okay... this discussion is more about threads than programmer certification, so I am going to move this to the threads forum. Henry
|
 |
 |
I agree. Here's the link: jrebel
|
|
subject: Doubt in Threads
|
|
|