Link to home
Start Free TrialLog in
Avatar of ku916
ku916

asked on

Servlet with thread

I have this servlet that executes a system cmd (like to run a perl script). Some of the perl scripts can take a very long time to finish and it would hold my servlet would not come back until they are done.

So I'm trying to use Thread, start() and run(). But all the examples I've found are Thread running applet.

Here is what I want to do

public class ExecServlet extends HttpServlet {
...
...
...
private void launchExecution(String runType, int statusID,
HttpServletRequest request,
HttpServletResponse response)
throws ServletException , IOException
{

StringBuffer launchStr = new StringBuffer();
launchStr.append("perl long_running.pl");

String retString = doServerCommand(launchStr.toString(), request);
if (retString.indexOf("Successfully Running") == -1) {
msgBean.setPrimaryMsg("Error Launching execution"
forward("/exec_err_msg.jsp", request, response);
} else {
StringBuffer s = new StringBuffer("Execution Launched!");
int strIdx = retString.indexOf("Log File is");
if (strIdx > -1) {
s.append("<P>" + retString.substring(strIdx) + "<P>");
}
msgBean.setPrimaryMsg(s.toString());
forward("/exec_msg.jsp", request, response);
}


private synchronized String doServerCommand(String cmd, HttpServletRequest request)
{
...
...
Process cmdProc = Runtime.getRuntime().exec(cmd);

// get its output (your input) stream
//
BufferedReader cmdIn = new BufferedReader(new InputStreamReader(cmdProc.getInputStream()));
BufferedReader cmdErr = new BufferedReader(new InputStreamReader(cmdProc.getErrorStream()));
try {
String inStr;
while (( inStr = cmdIn.readLine()) != null) {
cmdStdOutput.append(inStr + "\n");
}
while (( inStr = cmdErr.readLine()) != null) {
cmdErrOutput.append(inStr + "\n");
}
}
...
...  
 


ASKER CERTIFIED SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Threads work the same with servlets as with applets.
http://java.sun.com/docs/books/tutorial/essential/threads/index.html

You need to decide what happens if someone invokes the servlet before the process has finished, typically you would tell the user that the process is still executing. So you need to track if the thread is running or not.
No comment has been added lately, so it's time to clean up this TA.
I will leave a recommendation in the Cleanup topic area that this question is:

-- Points for CEHJ

Please leave any comments here within the next seven days.

PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!

TimYates
EE Cleanup Volunteer