Java RMI and Thread Synchronization questions

前端 未结 4 1506
鱼传尺愫
鱼传尺愫 2020-12-14 04:45

I actually have two questions about Java RMI and thread synchronization:

1) If I implement my RMI remote methods as synchronized, are they guaranteed to be mutually

4条回答
  •  渐次进展
    2020-12-14 05:34

    1. For each call from a RMI client the RMI server will execute the call in a new thread. You only need to synchronize access to shared objects.

    2. Another thread or timer will not stop your server from accepting calls from the client side. This needs synchronization, the best practice depends on how long the cleanup job runs can it be interrupted, or would it be possible to put the requests in a queue etc. The easiest way would be to let the RMI methods wait for the lock as already described by ewernli.

    EDIT: According to your comment, a skeleton that demonstrates how to achieve this kind of basic synchronization. Since everything is now mutually exclusive, you can't expect high performance with multiple clients involved. Anyway this would cover your requirements. (I hope). If your project grows you should read the Concurrency Tutorial

    Object mutex = new Object();
    
    int rmiMethod1() {
        synchronized (mutex) {
            doWhatNeeded1();
        }
    }
    
    int rmiMethod2() {
        synchronized (mutex) {
            doWhatNeeded2();
        }
    }
    
    // in your cleanup thread
    void run() {
        synchronized (mutex) {
            cleanUp();
        }
    }
    

提交回复
热议问题