View Javadoc

1   package com.atlassian.sal.core.executor;
2   
3   import com.atlassian.sal.core.executor.ThreadLocalContextManager;
4   
5   /**
6    * A delegating runnable that copies the thread local state into the executing thread.
7    *
8    * @since 2.0
9    */
10  class ThreadLocalDelegateRunnable implements Runnable
11  {
12      private final Object context;
13      private final Runnable delegate;
14      private final ThreadLocalContextManager manager;
15      private final ClassLoader contextClassLoader;
16  
17      /**
18       * @param manager The manager to get the context from
19       * @param delegate The runnable to delegate to
20       */
21      ThreadLocalDelegateRunnable(ThreadLocalContextManager manager, Runnable delegate)
22      {
23          this.delegate = delegate;
24          this.manager = manager;
25          this.context = manager.getThreadLocalContext();
26          this.contextClassLoader = Thread.currentThread().getContextClassLoader();
27      }
28  
29      public void run()
30      {
31          ClassLoader oldContextClassLoader = Thread.currentThread().getContextClassLoader();
32          try
33          {
34              Thread.currentThread().setContextClassLoader(contextClassLoader);
35              manager.setThreadLocalContext(context);
36              delegate.run();
37          }
38          finally
39          {
40              Thread.currentThread().setContextClassLoader(oldContextClassLoader);
41              manager.clearThreadLocalContext();
42          }
43      }
44  }