1 package com.atlassian.plugin.util;
2
3 import java.util.Deque;
4 import java.util.LinkedList;
5
6 /**
7 * This utility provides a thread local stack of {@link ClassLoader}s.
8 * The current "top" of the stack is the thread's current context class loader.
9 * This can be used when implementing delegating plugin {@link java.util.logging.Filter}s or {@link javax.servlet.Servlet}s
10 * that need to set the {@link ClassLoader} to the {@link com.atlassian.plugin.classloader.PluginClassLoader} the filter
11 * or servlet is declared in.
12 *
13 * @since 2.5.0
14 */
15 public class ClassLoaderStack
16 {
17 // We don't override initialValue as tomcat logs warnings if there is an object
18 // left in the thread local (even if it is an empty list)
19 private static final ThreadLocal<Deque<ClassLoader>> classLoaderStack = new ThreadLocal<Deque<ClassLoader>>();
20
21 /**
22 * Makes the given classLoader the new ContextClassLoader for this thread, and pushes the current ContextClassLoader
23 * onto a ThreadLocal stack so that we can do a {@link #pop} operation later to return to that ContextClassLoader.
24 *
25 * <p>
26 * Passing null is allowed and will act as a no-op. This means that you can safely {@link #pop} a ClassLoader and {@link #push} it back in
27 * and it will work safely whether the stack was empty at time of {@link #pop} or not.
28 *
29 * @param loader The new ClassLoader to set as ContextClassLoader.
30 */
31 public static void push(ClassLoader loader)
32 {
33 if (loader == null)
34 {
35 return;
36 }
37
38 Deque<ClassLoader> stack = classLoaderStack.get();
39 if (stack == null)
40 {
41 stack = new LinkedList<ClassLoader>();
42 classLoaderStack.set(stack);
43 }
44 stack.push(Thread.currentThread().getContextClassLoader());
45 Thread.currentThread().setContextClassLoader(loader);
46 }
47
48 /**
49 * Pops the current ContextClassLoader off the stack, setting the new ContextClassLoader to the previous one on the stack.
50 * <ul>
51 * <li>If the stack is not empty, then the current ClassLoader is replaced by the previous one on the stack, and then returned.</li>
52 * <li>If the stack is empty, then null is returned and the current ContextClassLoader is not changed.</li>
53 * </ul>
54 *
55 * @return the previous ContextClassLoader that was just replaced, or null if the stack is empty.
56 */
57 public static ClassLoader pop()
58 {
59 Deque<ClassLoader> stack = classLoaderStack.get();
60 if (stack == null || stack.isEmpty())
61 {
62 return null;
63 }
64 ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader();
65 Thread.currentThread().setContextClassLoader(stack.pop());
66 if (stack.isEmpty())
67 {
68 classLoaderStack.remove();
69 }
70
71 return currentClassLoader;
72 }
73 }