title: Java ExecutorService sequentially -Spring MVC
body: <p>I want to implement the ExecutorService in my Spring-MVC application.</p>
  
  <p>I need a global ExecutorService which take tasks put them in a queue and then executes them sequentially. So I want to pass the tasks from different locations in the application. Therefore I am using the <code>Executors.newSingleThreadExecutor();</code> so I have only 1 thread executing these tasks. </p>
  
  <p>However, I am not sure how to integrate it in a Spring application:</p>
  
  <pre><code>public enum TaskQueue {
  
      INSTANCE;
  
      ExecutorService executorService;
  
      private TaskQueue() {
          executorService = Executors.newSingleThreadExecutor();
      }
  
      public void addTaskToQueue (Runnable task){
          executorService.submit(task);
          executorService.shutdown();
      }
  }
  </code></pre>
  
  <p>So I am thinking of creating a Singleton and then just passing the Task (Runnable object) to the method:</p>
  
  <pre><code>TaskQueue.INSTANCE.addTaskToQueue(new Runnable() {
   @Override
    public void run() {
        System.out.println("Executing Task1 inside : " + Thread.currentThread().getName());
          }
      });
  </code></pre>
  
  <p>However, I have several questions:</p>
  
  <p>I am not sure how to integrate it in a Spring MVC application where I have controllers, services and so on.</p>
  
  <p>The application receives some notifications from a web-service. These notifications will be processed on different locations in the code. I want to 
  execute them sequentially. So I need to identify all tasks I want to run asynchronously and then pass them to the method above (`addTaskToQueue) wrapped in a Runnabel object, so they can be executed asynchronously. Is this the correct approach? </p>
  
  <p>So I always pass a Runnable objects to this method to execute it. This method executes it and shuts the executorservice down. So each time I pass a task to this service - it creates a new service and then closes it. But I dont want to have that - I want the executorservice to stay alive and execute the tasks that are comming and not shutdown after each task. How do I achieve this?</p>
  
  <p>Or am I totally wrong in implementing it this way?</p>
  
  <p>EDIT:</p>
  
  <p>Using the TaskExecutor provided by Spring - I would implement it like this:</p>
  
  <pre><code>@Autowired
  private TaskExecutor taskExecutor;
  </code></pre>
  
  <p>Then calling it from different location in my code:</p>
  
  <pre><code>taskExecutor.execute(new Runnable() {
          @Override
          public void run() {
              //TODO add long running task
          }
      });
  </code></pre>
  
  <p>Probably I need to make sure somewhere in the configuration that it needs to be executed sequentially - so it should create only 1 thread. Is it safe to call it from different locations? It wont always create a new service with a new queue?</p>