1 /** 2 * 3 * Copyright 2003-2004 The Apache Software Foundation 4 * 5 * Licensed under the Apache License, Version 2.0 (the "License"); 6 * you may not use this file except in compliance with the License. 7 * 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 18 package org.apache.geronimo.system.logging.log4j; 19 20 import java.util.HashMap; 21 import java.util.LinkedList; 22 import java.util.Map; 23 24 /** 25 * Provides named nested diagnotic contexts. 26 * 27 * @version $Rev: 355877 $ $Date: 2005-12-10 18:48:27 -0800 (Sat, 10 Dec 2005) $ 28 */ 29 public final class NamedNDC { 30 /** 31 * Mapping from names to NamedNDCs. 32 * Currently there is no way to remove a NamedNCD once created, so be sure you really 33 * want a new NDC before creating one. 34 * @todo make this a weak-valued map 35 */ 36 private static final Map contexts = new HashMap(); 37 38 /** 39 * Gets the NamedNDC by name, or creates a new one of one does not already exist. 40 * @param name the name of the desired NamedNDC 41 * @return the existing NamedNDC or a new one 42 */ 43 public static NamedNDC getNamedNDC(String name) { 44 synchronized (contexts) { 45 NamedNDC context = (NamedNDC) contexts.get(name); 46 if (context == null) { 47 context = new NamedNDC(); 48 contexts.put(name, context); 49 } 50 return context; 51 } 52 } 53 54 private final ListThreadLocal listThreadLocal = new ListThreadLocal(); 55 56 private NamedNDC() { 57 } 58 59 public void push(Object value) { 60 listThreadLocal.getList().addLast(value); 61 } 62 63 public Object get() { 64 LinkedList list = listThreadLocal.getList(); 65 if (list.isEmpty()) { 66 return null; 67 } 68 return list.getLast(); 69 } 70 71 public Object pop() { 72 LinkedList list = listThreadLocal.getList(); 73 if (list.isEmpty()) { 74 return null; 75 } 76 return list.removeLast(); 77 } 78 79 public void clear() { 80 listThreadLocal.getList().clear(); 81 } 82 83 private final static class ListThreadLocal extends ThreadLocal { 84 public LinkedList getList() { 85 return (LinkedList) get(); 86 } 87 88 protected Object initialValue() { 89 return new LinkedList(); 90 } 91 } 92 }