• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 package org.slf4j.helpers;
2 
3 import java.util.ArrayDeque;
4 import java.util.Deque;
5 import java.util.HashMap;
6 import java.util.Map;
7 
8 
9 /**
10  * A simple implementation of ThreadLocal backed Map containing values of type
11  * Deque<String>.
12  *
13  * @author Ceki Guuml;c&uuml;
14  * @since 2.0.0
15  */
16 public class ThreadLocalMapOfStacks {
17 
18     // BEWARE: Keys or values placed in a ThreadLocal should not be of a type/class
19     // not included in the JDK. See also https://jira.qos.ch/browse/LOGBACK-450
20 
21     final ThreadLocal<Map<String, Deque<String>>> tlMapOfStacks = new ThreadLocal<>();
22 
pushByKey(String key, String value)23     public void pushByKey(String key, String value) {
24         if (key == null)
25             return;
26 
27         Map<String, Deque<String>> map = tlMapOfStacks.get();
28 
29         if (map == null) {
30             map = new HashMap<>();
31             tlMapOfStacks.set(map);
32         }
33 
34         Deque<String> deque = map.get(key);
35         if (deque == null) {
36             deque = new ArrayDeque<>();
37         }
38         deque.push(value);
39         map.put(key, deque);
40     }
41 
popByKey(String key)42     public String popByKey(String key) {
43         if (key == null)
44             return null;
45 
46         Map<String, Deque<String>> map = tlMapOfStacks.get();
47         if (map == null)
48             return null;
49         Deque<String> deque = map.get(key);
50         if (deque == null)
51             return null;
52         return deque.pop();
53     }
54 
getCopyOfDequeByKey(String key)55     public Deque<String> getCopyOfDequeByKey(String key) {
56         if (key == null)
57             return null;
58 
59         Map<String, Deque<String>> map = tlMapOfStacks.get();
60         if (map == null)
61             return null;
62         Deque<String> deque = map.get(key);
63         if (deque == null)
64             return null;
65 
66         return new ArrayDeque<String>(deque);
67     }
68 
69     /**
70      * Clear the deque(stack) referenced by 'key'.
71      *
72      * @param key identifies the  stack
73      *
74      * @since 2.0.0
75      */
clearDequeByKey(String key)76     public void clearDequeByKey(String key) {
77         if (key == null)
78             return;
79 
80         Map<String, Deque<String>> map = tlMapOfStacks.get();
81         if (map == null)
82             return;
83         Deque<String> deque = map.get(key);
84         if (deque == null)
85             return;
86         deque.clear();
87     }
88 
89 }
90