Thread-safe way to call an external process (and g

2019-09-20 11:43发布

How do I call an external process in a thread safe way from inside an EJB?

ProcessBuilder is not thread safe, as stated in the javadoc. Apache commons exec says nothing about thread-safety and I am not confident in Runtime.exec either.

What's the proper way?

let me add some code so people won't think I am abusing, this code sometimes works, sometimes not

public int startTask(Logger logger, String expectPath, String expectScriptPath, long ticket) throws IOException {
    Runtime r = Runtime.getRuntime();
    Process p = r.exec(expectPath+" "+expectScriptPath+" "+ticket);

    SessionLogger sysout = new SessionLogger(logger,p.getInputStream());
    sysout.start();

    SessionLogger syserr = new SessionLogger(logger,p.getErrorStream());
    syserr.start();

    try {
        return p.waitFor();
    } catch (InterruptedException e) {
        log.error(e.getMessage(),e);
        return -1;
    }

}

please don't close or downvote this question.

I know it's not thread safe. I just want to know how do it properly from inside an EJB.

1条回答
等我变得足够好
2楼-- · 2019-09-20 12:23

One of the points of EJBs is precisely that you don't have to worry about concurrency, you are guaranteed that only one thread will be invoking your EJB method at any given time. ProcessBuilder doesn't have to be thread-safe, as long as you don't make it static nor share the same instance between different instances of your EJBs.

查看更多
登录 后发表回答