|
| 1 | +/** |
| 2 | + * Copyright (C) 2013-2022 Red Hat, Inc. (https://github.com/Commonjava/weft) |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | +package org.commonjava.o11yphant.common.thread; |
| 17 | + |
| 18 | +import org.slf4j.Logger; |
| 19 | +import org.slf4j.LoggerFactory; |
| 20 | +import org.slf4j.MDC; |
| 21 | + |
| 22 | +import java.util.ArrayList; |
| 23 | +import java.util.Collection; |
| 24 | +import java.util.List; |
| 25 | +import java.util.Map; |
| 26 | +import java.util.Set; |
| 27 | +import java.util.concurrent.ConcurrentHashMap; |
| 28 | +import java.util.function.BiConsumer; |
| 29 | +import java.util.function.BiFunction; |
| 30 | +import java.util.function.Consumer; |
| 31 | +import java.util.function.Function; |
| 32 | + |
| 33 | +/** |
| 34 | + * (Copied from weft: https://github.com/Commonjava/weft) |
| 35 | + * |
| 36 | + * This {@link ThreadContext} keeps a count of the number of threads referencing it, and can run finalization logic |
| 37 | + * when that number hits 0. |
| 38 | + * |
| 39 | + * Created by jdcasey on 1/3/17. |
| 40 | + */ |
| 41 | +public class ThreadContext |
| 42 | + implements Map<String, Object> |
| 43 | +{ |
| 44 | + private static ThreadLocal<ThreadContext> THREAD_LOCAL = new ThreadLocal<>(); |
| 45 | + |
| 46 | + private final Map<String, Object> contextMap = new ConcurrentHashMap<>(); |
| 47 | + |
| 48 | + private Map<String, String> mdcMap; // mapped diagnostic context |
| 49 | + |
| 50 | + private int refs = 1; |
| 51 | + |
| 52 | + private List<Consumer<ThreadContext>> finalizers = new ArrayList<>(); |
| 53 | + |
| 54 | + public static ThreadContext getContext( boolean create ) |
| 55 | + { |
| 56 | + ThreadContext threadContext = THREAD_LOCAL.get(); |
| 57 | + if ( threadContext == null && create ) |
| 58 | + { |
| 59 | + threadContext = new ThreadContext(); |
| 60 | + THREAD_LOCAL.set( threadContext ); |
| 61 | + } |
| 62 | + |
| 63 | + if ( threadContext != null ) |
| 64 | + { |
| 65 | + threadContext.mdcMap = MDC.getCopyOfContextMap(); |
| 66 | + } |
| 67 | + |
| 68 | + return threadContext; |
| 69 | + } |
| 70 | + |
| 71 | + public static ThreadContext setContext( ThreadContext ctx ) |
| 72 | + { |
| 73 | + ThreadContext oldCtx = swapContext( ctx ); |
| 74 | + if ( ctx != null && ctx.mdcMap != null ) |
| 75 | + { |
| 76 | + MDC.setContextMap(ctx.mdcMap); |
| 77 | + } |
| 78 | + return oldCtx; |
| 79 | + } |
| 80 | + |
| 81 | + private static ThreadContext swapContext( final ThreadContext ctx ) |
| 82 | + { |
| 83 | + ThreadContext oldCtx = THREAD_LOCAL.get(); |
| 84 | + if ( oldCtx != null ) |
| 85 | + { |
| 86 | + Logger logger = LoggerFactory.getLogger( ThreadContext.class ); |
| 87 | + oldCtx.refs--; |
| 88 | + logger.trace( "context refs: {}", oldCtx.refs ); |
| 89 | + oldCtx.runFinalizersIfDone(); |
| 90 | + } |
| 91 | + |
| 92 | + if ( ctx != null ) |
| 93 | + { |
| 94 | + THREAD_LOCAL.set( ctx ); |
| 95 | + ctx.refs++; |
| 96 | + } |
| 97 | + else |
| 98 | + { |
| 99 | + THREAD_LOCAL.remove(); |
| 100 | + } |
| 101 | + |
| 102 | + return oldCtx; |
| 103 | + } |
| 104 | + |
| 105 | + /** |
| 106 | + * Provide some finalizer logic to handle the scenario where the number of "live" threads referencing this context |
| 107 | + * drops to 0. Before this happens, any contextual information in this ThreadContext may be needed by running threads, |
| 108 | + * and it's not safe to clean up. However, since the context may contain {@link java.io.Closeable} instances and |
| 109 | + * the like, it's important to have some point where they will be cleaned up. |
| 110 | + * @since 1.5 |
| 111 | + * @param finalizer |
| 112 | + */ |
| 113 | + public synchronized void registerFinalizer( Consumer<ThreadContext> finalizer ) |
| 114 | + { |
| 115 | + if ( !this.finalizers.contains( finalizer ) ) |
| 116 | + { |
| 117 | + Logger logger = LoggerFactory.getLogger( getClass() ); |
| 118 | + logger.debug( "Registering finalizer: {} on ThreadContext: {}", finalizer, this ); |
| 119 | + this.finalizers.add( finalizer ); |
| 120 | + } |
| 121 | + } |
| 122 | + |
| 123 | + /** |
| 124 | + * If the thread reference count on this context drops to zero, run any finalization logic that might be registered. |
| 125 | + */ |
| 126 | + private synchronized void runFinalizersIfDone() |
| 127 | + { |
| 128 | + Logger logger = LoggerFactory.getLogger( getClass() ); |
| 129 | + if ( refs < 1 && finalizers != null ) |
| 130 | + { |
| 131 | + logger.debug( "Running finalizers for ThreadContext: {}", this ); |
| 132 | + finalizers.forEach( c->{ |
| 133 | + if ( c != null ) |
| 134 | + { |
| 135 | + logger.debug( "Running finalizer: {} for ThreadContext: {}", c, this ); |
| 136 | + |
| 137 | + try |
| 138 | + { |
| 139 | + c.accept( this ); |
| 140 | + } |
| 141 | + catch ( Throwable t ) |
| 142 | + { |
| 143 | + logger.error( "Caught error while running finalizer: " + c + " on ThreadContext: " + this, t ); |
| 144 | + } |
| 145 | + |
| 146 | + logger.trace( "Finalizer: {} done for ThreadContext: {}", c, this ); |
| 147 | + } |
| 148 | + } ); |
| 149 | + } |
| 150 | + } |
| 151 | + |
| 152 | + public static void clearContext() |
| 153 | + { |
| 154 | + swapContext( null ); |
| 155 | + MDC.clear(); |
| 156 | + } |
| 157 | + |
| 158 | + private ThreadContext(){} |
| 159 | + |
| 160 | + public int size() |
| 161 | + { |
| 162 | + return contextMap.size(); |
| 163 | + } |
| 164 | + |
| 165 | + public boolean isEmpty() |
| 166 | + { |
| 167 | + return contextMap.isEmpty(); |
| 168 | + } |
| 169 | + |
| 170 | + public void putAll( Map<? extends String, ?> map ) |
| 171 | + { |
| 172 | + contextMap.putAll( map ); |
| 173 | + } |
| 174 | + |
| 175 | + public Collection<Object> values() |
| 176 | + { |
| 177 | + return contextMap.values(); |
| 178 | + } |
| 179 | + |
| 180 | + public Object merge( String key, Object value, BiFunction<? super Object, ? super Object, ?> remappingFunction ) |
| 181 | + { |
| 182 | + return contextMap.merge( key, value, remappingFunction ); |
| 183 | + } |
| 184 | + |
| 185 | + public Set<String> keySet() |
| 186 | + { |
| 187 | + return contextMap.keySet(); |
| 188 | + } |
| 189 | + |
| 190 | + public void forEach( BiConsumer<? super String, ? super Object> action ) |
| 191 | + { |
| 192 | + contextMap.forEach( action ); |
| 193 | + } |
| 194 | + |
| 195 | + public Object computeIfPresent( String key, BiFunction<? super String, ? super Object, ?> remappingFunction ) |
| 196 | + { |
| 197 | + return contextMap.computeIfPresent( key, remappingFunction ); |
| 198 | + } |
| 199 | + |
| 200 | + public void clear() |
| 201 | + { |
| 202 | + contextMap.clear(); |
| 203 | + } |
| 204 | + |
| 205 | + public boolean containsValue( Object o ) |
| 206 | + { |
| 207 | + return contextMap.containsValue( o ); |
| 208 | + } |
| 209 | + |
| 210 | + public Object put( String s, Object o ) |
| 211 | + { |
| 212 | + return contextMap.put( s, o ); |
| 213 | + } |
| 214 | + |
| 215 | + public void replaceAll( BiFunction<? super String, ? super Object, ?> function ) |
| 216 | + { |
| 217 | + contextMap.replaceAll( function ); |
| 218 | + } |
| 219 | + |
| 220 | + public Object get( Object o ) |
| 221 | + { |
| 222 | + return contextMap.get( o ); |
| 223 | + } |
| 224 | + |
| 225 | + public boolean containsKey( Object o ) |
| 226 | + { |
| 227 | + return contextMap.containsKey( o ); |
| 228 | + } |
| 229 | + |
| 230 | + public Set<Entry<String, Object>> entrySet() |
| 231 | + { |
| 232 | + return contextMap.entrySet(); |
| 233 | + } |
| 234 | + |
| 235 | + public boolean replace( String key, Object oldValue, Object newValue ) |
| 236 | + { |
| 237 | + return contextMap.replace( key, oldValue, newValue ); |
| 238 | + } |
| 239 | + |
| 240 | + public Object computeIfAbsent( String key, Function<? super String, ?> mappingFunction ) |
| 241 | + { |
| 242 | + return contextMap.computeIfAbsent( key, mappingFunction ); |
| 243 | + } |
| 244 | + |
| 245 | + public Object compute( String key, BiFunction<? super String, ? super Object, ?> remappingFunction ) |
| 246 | + { |
| 247 | + return contextMap.compute( key, remappingFunction ); |
| 248 | + } |
| 249 | + |
| 250 | + public Object putIfAbsent( String key, Object value ) |
| 251 | + { |
| 252 | + return contextMap.putIfAbsent( key, value ); |
| 253 | + } |
| 254 | + |
| 255 | + public Object remove( Object o ) |
| 256 | + { |
| 257 | + return contextMap.remove( o ); |
| 258 | + } |
| 259 | + |
| 260 | + public Object getOrDefault( Object key, Object defaultValue ) |
| 261 | + { |
| 262 | + return contextMap.getOrDefault( key, defaultValue ); |
| 263 | + } |
| 264 | + |
| 265 | + public boolean remove( Object key, Object value ) |
| 266 | + { |
| 267 | + return contextMap.remove( key, value ); |
| 268 | + } |
| 269 | + |
| 270 | + public Object replace( String key, Object value ) |
| 271 | + { |
| 272 | + return contextMap.replace( key, value ); |
| 273 | + } |
| 274 | + |
| 275 | +} |
0 commit comments