0

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.

Leo
  • 6,480
  • 4
  • 37
  • 52

1 Answers1

2

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.

Camilo
  • 1,889
  • 2
  • 17
  • 16
  • thanks for answering. Well, I agree with you, that's the EJB idea. But after running this code in several MDBs, I am getting some strange errors that I can't reproduce, so my first suspect is the Runtime.exec. Do you think if I call a ProcessBuilder instead from inside a stateless EJB, it would be enough to be thread-safe? – Leo Feb 13 '14 at 04:05
  • actually `Runtime.exec` should do the job just as well, can you post the error you're getting? – Camilo Feb 13 '14 at 04:11
  • that's the problem. no exception is thrown. but when 10 MDBs consuming from a JMS queue start, each one, a runtime.exec, somehow it´s messing with the results. Let me try to isolate the problem to post here. Thanks – Leo Feb 13 '14 at 09:09