View Javadoc

1   package com.atlassian.plugin.servlet.util;
2   
3   import java.util.LinkedList;
4   import java.util.List;
5   
6   /**
7    * This utility provides a thread local stack of {@link ClassLoader}s.  The current "top" of the stack is the 
8    * threads current context class loader.  This can be used when implementing delegating plugin {@link Filter}s or 
9    * {@link Servlet}s that need to set the {@link ClassLoader} to the {@link PluginClassLoader} the filter or servlet is
10   * declared in.
11   * 
12   * @since 2.1.0
13   */
14  public class ClassLoaderStack
15  {
16      private static final ThreadLocal<List<ClassLoader>> classLoaderStack = new ThreadLocal<List<ClassLoader>>()
17      {
18          protected List<ClassLoader> initialValue()
19          {
20              return new LinkedList<ClassLoader>();
21          }
22      };
23      
24      public static void push(ClassLoader loader)
25      {
26          classLoaderStack.get().add(0, Thread.currentThread().getContextClassLoader());
27          Thread.currentThread().setContextClassLoader(loader);
28      }
29      
30      public static void pop()
31      {
32          Thread.currentThread().setContextClassLoader(classLoaderStack.get().remove(0));
33      }
34  }