java rmi死锁

发布于 2024-11-26 15:37:53 字数 639 浏览 2 评论 0原文

我刚刚开始使用 java rmi 进行编程,我在代码中遇到以下问题:

我的服务器有两种远程方法,通常实现如下:

public class ServerImpl extends UnicastRemoteObject implements Server{
      ....
      Synchronized void  foo(){ aClient.Foo3();}
      Synchronized void  foo1(){ .... }
 }

我的客户端有一个远程方法,其实现如下:

public class ClientImpl extends UnicastRemoteObject implements Client{
      ....
      void Foo3(){theServer.foo1();}
}

因此,当 aClient 调用服务器的foo(),服务器调用客户端的 Foo3(),然后 aClient 想要调用服务器的 foo1(),我们遇到了死锁(服务器和客户端都没有继续)。我知道这是由于 Synchronized 关键字引起的。问题是这些方法必须是同步的(我不想同时有两个线程),而且我完全不知道如何解决这个问题。任何帮助表示赞赏。

非常感谢!

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

锦爱 2024-12-03 15:37:53

您可以在每个方法内使用具有不同锁定对象的同步块。 synchronized 方法锁定 this,因此一次只能访问一个。

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.

无敌元气妹 2024-12-03 15:37:53

当 RMI 中有客户端回调时,它会在与调用执行回调的服务器 RMI 方法的线程不同的线程上调用。因此,如果回调方法随后调用服务器上的另一个同步方法,我们就会陷入死锁,因为您已经处于服务器上的一个同步方法中。

因此,同步可能会导致死锁,如果所有方法调用都是本地而不是远程,则不会出现死锁。您需要使同步更加细粒度:在需要同步的实际内部对象上进行同步,而不是通过同步方法在 RMI 服务器对象本身上进行同步。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文