View Javadoc

1   package com.atlassian.plugin.osgi.spring;
2   
3   import org.springframework.core.task.AsyncTaskExecutor;
4   
5   import java.util.concurrent.ExecutorService;
6   import java.util.concurrent.Executors;
7   import java.util.concurrent.ThreadFactory;
8   import java.util.concurrent.atomic.AtomicInteger;
9   
10  /**
11   * Executes spring tasks using a cached thread pool that expands as necessary.  Overrides the default Spring executor
12   * that spawns a new thread for every application context creation.
13   *
14   * @since 2.5.0
15   */
16  public class ThreadPoolAsyncTaskExecutor implements AsyncTaskExecutor
17  {
18      private final ExecutorService executor = Executors.newCachedThreadPool(new NamedThreadFactory());
19  
20      /**
21       * Executes the runnable
22       * @param task The runnable task
23       * @param startTimeout The start timeout (ignored)
24       */
25      public void execute(Runnable task, long startTimeout)
26      {
27          // yes, we ignore the start timeout
28          executor.execute(task);
29      }
30  
31      /**
32       * Executes the runnable
33       * @param task The runnable task
34       */
35      public void execute(Runnable task)
36      {
37          this.execute(task, -1);
38      }
39  
40      /**
41       * Thread factory that names the threads for the executor
42       */
43      private static class NamedThreadFactory implements ThreadFactory
44      {
45          private final AtomicInteger counter = new AtomicInteger();
46          public Thread newThread(Runnable r)
47          {
48              Thread thread = new Thread(r);
49              thread.setDaemon(false);
50              thread.setName("Spring executor " + counter.incrementAndGet());
51              return thread;
52          }
53      }
54  }