RServe Java multiple threads (Unix)

September 13, 2016

(This article was first published on R – StudyTrails, and kindly contributed to R-bloggers)


On a unix environment it is possible for a threaded java application to call a single RServe instance. For each new connection RServe forks a new process. Each new connection has its own working directory. The working directory is retained if it is non empty, even when the connection is closed.

Example Program

The first step is starting the RServe instance.

R cmd Rserve --RS-port 1000

Here’s the java threaded java code that uses the Rserve instance to service four java threads. The program solves a linear model.

package com.studytrails.rserve;

public class RServeMultiThreadClient {
	public static void main(String[] args) {
		RServeMultiThread thread1 = new RServeMultiThread(1000);
		RServeMultiThread thread2 = new RServeMultiThread(1000);
		RServeMultiThread thread3 = new RServeMultiThread(1000);
		RServeMultiThread thread4 = new RServeMultiThread(1000);


		try {
		} catch (InterruptedException e) {

package com.studytrails.rserve;

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

public class RServeMultiThread extends Thread {

	private int port = 0;

	public RServeMultiThread(int port) {
		this.port = port;

	public void run() {
		try {
			RConnection c = new RConnection("localhost", port);
			c.eval("N = " + port);
			c.eval("x2 = 1 + x1 + rnorm(N)");
			c.eval("y <- 1 + x1 + x2");
			c.eval("df <- data.frame(y,x1,x2)");
			c.eval("fit <- lm(y ~ x1 + x2, data = df)");
			REXP x1 = c.eval("fit[[1]][2]");
			System.out.println("Thread with port " + port + " result: "
					+ x1.asDouble());
		} catch (RserveException e1) {
		} catch (InterruptedException e) {
		} catch (REXPMismatchException e) {

The post RServe Java multiple threads (Unix) appeared first on StudyTrails.

To leave a comment for the author, please follow the link and comment on their blog: R – StudyTrails. offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.

Search R-bloggers


Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)