View Javadoc

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