Search code examples
javarrserve

Rserve hangs when oppening multiple connections


I start Rserve:

C:\Program Files\R\R-3.5.0\bin\x64> "C:\Users\XXXX\DOCUME~1\R\WIN-LI~1\3.5\Rserve\libs\x64\Rserve.exe" --RS-port 1000

Run the following java code:

import org.rosuda.REngine.REXPMismatchException;
import org.rosuda.REngine.Rserve.RConnection;
import org.rosuda.REngine.Rserve.RserveException;

public class TestR {
    private  RConnection con;
    private  RConnection con2;
    public TestR(){
        try {
            con = new RConnection();
            con2 = new RConnection();
        } catch (RserveException e) {
            e.printStackTrace();
        }
    }
    public Double test(){
        try {

            double d = con.eval("1+1").asDouble();
            double c = con2.eval("1+1").asDouble();
            return d+c;
        } catch (RserveException | REXPMismatchException e) {
            return (double)(-1);
        }
    }
}

I created the following class on JUnit to test it:

import org.junit.Test;

import static org.junit.Assert.*;

public class TestRTest {

    @Test
    public void test(){
        TestR t = new TestR();
        t.test();
    }

}

When I run this test, it stops while instaciating the connections, it creates the first one, but does hangs on the second. Any idea why this could be happening?

First, no connections established

ok

Second, one connection established

ok

Hangs on second connection

hangs


Solution

  • Your issue might be related to a problem with Multithreading.

    Unix: no problem, one Rserve instance can serve mulitple calls.

    Windows: Rserve can't create a seperate process by forking the current process. --> create a new Rserve process for each thread (listening on a different port), a new Rserve connection on the corresponding port has to be established as well.

    RConnection connection = new RConnection(HOST, PORT);

    If you need more input, do not hesitate to ask. I can also provide my full class code for creating several R instances with Rserve if you want to.

    See this Java class I used to run several instances of R with Rserve.