Reputation: 23
I just have started to program with java rmi and I face the following problem in my code:
My server has two Remote methods which are implemented in general as follows:
public class ServerImpl extends UnicastRemoteObject implements Server{
....
Synchronized void foo(){ aClient.Foo3();}
Synchronized void foo1(){ .... }
}
My clients have one remote method which is implemented as follows:
public class ClientImpl extends UnicastRemoteObject implements Client{
....
void Foo3(){theServer.foo1();}
}
So when aClient calls server's foo(), the server calls client's Foo3() and then aClient wants to call server's foo1() and we have a deadlock (neither the server nor the client moves on). I know that this is caused because of the Synchronized keyword. The problem is that these methods have to be Synchronized (I don't want two threads the same time in there), and I don't have the slightest idea of how to resolve this issue. Any help appreciated.
Thank you very much!
Upvotes: 2
Views: 1082
Reputation: 310980
When you have a client callback in RMI, it gets invoked on a different thread from the thread that invoked the server RMI method that did the callback. So if the callback method then calls another synchronized method at the server we have a deadlock, because you're already in one at the server.
So synchronized
can cause a deadlock that wouldn't arise if all the method calls were local instead of remote. You need to make your synchronization more fine-grained: synchronize on the actual internal objects that need it, rather than on the RMI server object itself via synchronized methods.
Upvotes: 2
Reputation: 23184
You can use a synchronized block with different locking object inside each method. synchronized
methods lock on this
so only one may be visited at a time.
Upvotes: 3