damians
damians

Reputation: 13

run only single thread in the method

I have a application in Spring MVC. In controller, user can run process(has button). Process working for one hour ( name it "longProces") . So I want to run this method "longProces" in other thread.

When "longProces" is running, other user (when he want to run "longProces") should get message: "this process is running" and his thread is killed (not waiting for it turn).

What can I do this? Any idea?

Thank for answer

Upvotes: 0

Views: 5822

Answers (3)

Priya Singh
Priya Singh

Reputation: 66

You can use ExecutorService instead of Executor.

Submit the task in executor service and maintain Future references say in some list or map. ExecutorService threadExecutor = Executors.newSingleThreadExecutor(); Future future = threadExecutor.submit(new Task()); //submit the future in collection

on every new request you can check already submitted task and there status if completed-

 //retrieve future instance from collection
 if(future.isDone()){ 
      //accept new request
 }
 else "process already running"

Upvotes: 1

damians
damians

Reputation: 13

Below is my sniped code:

@RequestMapping("/generate")
public String generate(HttpServletResponse response, Model model) throws Exception {
    String communique; = "The process is launching";

    Runnable runnable = () -> {
        try {
            generatorService.runLongProces();
        } catch (IOException e) {
            e.printStackTrace();
        }
    };

    Executor tasExecutor = Executors.newSingleThreadExecutor();

    try{
    tasExecutor.execute(runnable);

    } catch (Exception ex)
    {
     communique = "The process is failed";
    }

    response.setStatus(HttpServletResponse.SC_ACCEPTED);

    model.addAttribute("communique", communique);

    return "institutions/download";
}

I thought I set one thread in the constructor.

Maybe I should create a singleton bean for Spring TaskExecutor ?

Upvotes: 0

Pandian
Pandian

Reputation: 151

It is a design based question.

For this scenario, my straight forward solution is - maintain this long process status in database or any other persistence layer so that you can implement logic for every request first check is there any long process is active or not in the persistence. Based on this condition you can decide you flow.

One more critical point is, persistence layer approach would be the right solution to handle the multiple user request with one common shared process.

Upvotes: 0

Related Questions