001 /* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache license, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the license for the specific language governing permissions and 015 * limitations under the license. 016 */ 017 package org.apache.logging.log4j.util; 018 019 import java.security.AccessController; 020 import java.security.PrivilegedAction; 021 022 /** 023 * <em>Consider this class private.</em> Utility class for ClassLoaders. 024 * @see ClassLoader 025 * @see Thread#getContextClassLoader() 026 */ 027 // TODO: migrate any other useful methods from Loader in log4j-core 028 public final class LoaderUtil { 029 private LoaderUtil() {} 030 031 private static final PrivilegedAction<ClassLoader> TCCL_GETTER = new ThreadContextClassLoaderGetter(); 032 033 static { 034 final SecurityManager sm = System.getSecurityManager(); 035 if (sm != null) { 036 sm.checkPermission(new RuntimePermission("getClassLoader")); 037 } 038 } 039 040 /** 041 * Gets the current Thread ClassLoader. Returns the system ClassLoader if the TCCL is {@code null}. 042 * 043 * @return the current ThreadContextClassLoader. 044 */ 045 public static ClassLoader getThreadContextClassLoader() { 046 return System.getSecurityManager() == null 047 ? TCCL_GETTER.run() 048 : AccessController.doPrivileged(TCCL_GETTER); 049 } 050 051 private static class ThreadContextClassLoaderGetter implements PrivilegedAction<ClassLoader> { 052 @Override 053 public ClassLoader run() { 054 final ClassLoader cl = Thread.currentThread().getContextClassLoader(); 055 // if the TCCL is null, that means we're using the system CL 056 return cl == null ? ClassLoader.getSystemClassLoader() : cl; 057 } 058 } 059 }