title: Submitting a background task from spring mvc app
body: <p>I've got working spring MVC app and what I'm trying to do next is to start or submit a background task from my app.</p>
  
  <p>Basically I'd like to keep the task going until it completes even if the user decides to do something else on the app.</p>
  
  <p>But also I'd like to stop/kill/pause the task if I needed to. Since I haven't done this before I'm looking for a good/better way to do this.</p>
  
  <p>I found these to be useful:</p>
  
  <p><a href="http://blog.springsource.com/2010/01/05/task-scheduling-simplifications-in-spring-3-0/" rel="nofollow noreferrer">http://blog.springsource.com/2010/01/05/task-scheduling-simplifications-in-spring-3-0/</a></p>
  
  <p><a href="https://stackoverflow.com/questions/671049/how-do-you-kill-a-thread-in-java">How do you kill a thread in Java?</a></p>
  
  <p><a href="https://stackoverflow.com/questions/181615/java-threads-is-it-possible-view-pause-kill-a-particular-thread-from-a-differen">Java threads: Is it possible view/pause/kill a particular thread from a different java program running on the same JVM?</a></p>
  
  <p>So I wanted to use @Async task to submit my background task, but wanted to use threads' id to obtain it later on and stop it if needed?</p>
  
  <p>Is this the right approach? I don't have any experience with multithreading so I'm here to listen.</p>
  
  <p><strong>Code update :</strong></p>
  
  <pre><code>public interface Worker {
      public void work();
      public void cancel();
  }
  </code></pre>
  
  <p>implementation :</p>
  
  <pre><code>@Component("asyncWorker")
  public class AsyncWorker implements Worker {
  
      @Async
      public void work() {
          String threadName = Thread.currentThread().getName();
          System.out.println("   " + threadName + " beginning work");
          try {
                  Thread.sleep(10000); // simulates work
          } catch (InterruptedException e) {
              System.out.println("I stopped");
          }
          System.out.println("   " + threadName + " completed work");
      }
  
      public void cancel() { Thread.currentThread().interrupt(); }
  }
  </code></pre>
  
  <p>Controller for testing purposes :</p>
  
  <pre><code>@ResponseBody
  @RequestMapping("/job/start")
  public String start() {
      asyncWorker.work();
      return "start";
  }
  
  @ResponseBody
  @RequestMapping("/job/stop")
  public String stop() {
      asyncWorker.cancel();
      return "stop";
  }
  </code></pre>
  
  <p>When I visit <code>/job/start</code>, I can't execute more that one task simultaneously. The other one starts to execute only after first one has completed</p>
  
  <p>Also when I visit <code>/job/stop</code> the process isn't stopped, what am I missing here?</p>