1

I have a task that I want to wrap in a servlet to provide the ability to run the task remotely, by http request.

I know I can achieve this with REST API, but currently I assume (and please correct me if I'm wrong) that a simple servlet will do.

One of the things I want to achieve is that if a request to the servlet is made while another request is still processed, I'll get an appropriate response - "Task is already running".

I've built a simple servlet, using servlet-3.0, that calls the jar I want to run, but when I make 2 requests, the second one is not processed until the first one is finished.

EDIT:

My servlet is a simple http serlvet. service method overriden. I have a system.out.println("a") in the start. when I call the servlet in debug mode and then (while stopped at breakpoint) call it again, the message is printed only one time and printed the second time when I release the breakpoint and the first run finishes.

4

2 回答 2

0

首先,这看起来根本不像 REST。如果您真的只想生成一个(单个)后台任务,请确保在单独的工作线程中执行,而不是在请求线程中执行。

于 2013-03-20T07:15:45.187 回答
0

也许你需要一把锁:

public class Task extends HttpServlet {
    // for singleton
    //private volatile boolean running = false;

    // or try this:

    public static boolean running = false;

    public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
    {
        if(running){
             PrintWriter out = response.getWriter();
             out.println("running");
             return;
        }
        synchronized(Task.class){
            if(!running){
                running = true;
                // run the task
                running = false;
            }
        }
    }
}
于 2013-03-20T07:17:30.110 回答