View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements. See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache license, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License. You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the license for the specific language governing permissions and
15   * limitations under the license.
16   */
17  package org.apache.logging.log4j.util;
18  
19  import java.security.AccessController;
20  import java.security.PrivilegedAction;
21  
22  /**
23   * <em>Consider this class private.</em> Utility class for ClassLoaders.
24   * @see ClassLoader
25   * @see Thread#getContextClassLoader()
26   */
27  // TODO: migrate any other useful methods from Loader in log4j-core
28  public final class LoaderUtil {
29      private LoaderUtil() {}
30  
31      private static final PrivilegedAction<ClassLoader> TCCL_GETTER = new ThreadContextClassLoaderGetter();
32  
33      static {
34          final SecurityManager sm = System.getSecurityManager();
35          if (sm != null) {
36              sm.checkPermission(new RuntimePermission("getClassLoader"));
37          }
38      }
39  
40      /**
41       * Gets the current Thread ClassLoader. Returns the system ClassLoader if the TCCL is {@code null}.
42       *
43       * @return the current ThreadContextClassLoader.
44       */
45      public static ClassLoader getThreadContextClassLoader() {
46          return System.getSecurityManager() == null
47              ? TCCL_GETTER.run()
48              : AccessController.doPrivileged(TCCL_GETTER);
49      }
50  
51      private static class ThreadContextClassLoaderGetter implements PrivilegedAction<ClassLoader> {
52          @Override
53          public ClassLoader run() {
54              final ClassLoader cl = Thread.currentThread().getContextClassLoader();
55              // if the TCCL is null, that means we're using the system CL
56              return cl == null ? ClassLoader.getSystemClassLoader() : cl;
57          }
58      }
59  }