Search code examples
javamultithreadingthreadpoolrmi

Is it possible to run remote calls to two different methods in the same thread in Java RMI?


Suppose that Remote class RemoteServer has two remote methods method1 and method2.

Is it possible to run the remote calls to these two methods in the same thread of the server in Java RMI?

It is known that method1 will be called first.


I have read "Thread Usage in Remote Method Invocations" (below) and have no ideas.

A method dispatched by the RMI runtime to a remote object implementation may or may not execute in a separate thread. The RMI runtime makes no guarantees with respect to mapping remote object invocations to threads.


Solution

  • Though your question indicates that there's a good chance you can find better program design, if you really need such functionality, you can implement it by means of ThreadPoolExecutor with a single thread. Just wrap your methods method1() and method2() into two different Callable's and submit them to your single-threaded pool.

    class Method1Task implements Callable<Void> {
        public Void call() throws Exception {
            // method 1 body here
            return null;
        }
    }
    
    class Method2Task implements Callable<Void> {
        public Void call() throws Exception {
            // method 2 body here
            return null;
        }
    }
    
    ...
    
    // Create a single-thread pool and use it to submit tasks
    private final ExecutorService executor = Executors.newFixedThreadPool(1);
    
    void method1() {
        executor.submit(new Method1Task());
    }
    
    void method2() {
        executor.submit(new Method2Task());
    }
    

    If you need to wait for method completions, use Futures that are returned by submit()s. If you need to return values from the methods, change Void for appropriate data types.

    In Java 8 it's simpler, you don't need the Callables:

    executor.submit(() -> {
        // call the method you need here
    });