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 018package org.apache.logging.log4j.core.async; 019 020import org.apache.logging.log4j.status.StatusLogger; 021import org.apache.logging.log4j.util.PropertiesUtil; 022 023/** 024 * Strategy for deciding whether thread name should be cached or not. 025 */ 026public enum ThreadNameCachingStrategy { // LOG4J2-467 027 CACHED { 028 @Override 029 public String getThreadName() { 030 String result = THREADLOCAL_NAME.get(); 031 if (result == null) { 032 result = Thread.currentThread().getName(); 033 THREADLOCAL_NAME.set(result); 034 } 035 return result; 036 } 037 }, 038 UNCACHED { 039 @Override 040 public String getThreadName() { 041 return Thread.currentThread().getName(); 042 } 043 }; 044 045 private static final StatusLogger LOGGER = StatusLogger.getLogger(); 046 private static final ThreadLocal<String> THREADLOCAL_NAME = new ThreadLocal<>(); 047 048 abstract String getThreadName(); 049 050 public static ThreadNameCachingStrategy create() { 051 final String defaultStrategy = System.getProperty("java.version").compareTo("1.8.0_102") < 0 052 ? "CACHED" // LOG4J2-2052 JDK 8u102 removed the String allocation in Thread.getName() 053 : "UNCACHED"; 054 final String name = PropertiesUtil.getProperties().getStringProperty("AsyncLogger.ThreadNameStrategy"); 055 try { 056 final ThreadNameCachingStrategy result = ThreadNameCachingStrategy.valueOf( 057 name != null ? name : defaultStrategy); 058 LOGGER.debug("AsyncLogger.ThreadNameStrategy={} (user specified {}, default is {})", 059 result, name, defaultStrategy); 060 return result; 061 } catch (final Exception ex) { 062 LOGGER.debug("Using AsyncLogger.ThreadNameStrategy.{}: '{}' not valid: {}", 063 defaultStrategy, name, ex.toString()); 064 return ThreadNameCachingStrategy.valueOf(defaultStrategy); 065 } 066 } 067}