View Javadoc
1   /**
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2015, QOS.ch. All rights reserved.
4    *
5    * This program and the accompanying materials are dual-licensed under
6    * either the terms of the Eclipse Public License v1.0 as published by
7    * the Eclipse Foundation
8    *
9    *   or (per the licensee's choosing)
10   *
11   * under the terms of the GNU Lesser General Public License version 2.1
12   * as published by the Free Software Foundation.
13   */
14  package ch.qos.logback.classic.turbo;
15  
16  import java.util.LinkedHashMap;
17  import java.util.Map;
18  
19  /**
20   * Clients of this class should only use the  {@link #getMessageCountAndThenIncrement} method. 
21   * Other methods inherited via LinkedHashMap are not thread safe.
22   */
23  class LRUMessageCache extends LinkedHashMap<String, Integer> {
24  
25      private static final long serialVersionUID = 1L;
26      final int cacheSize;
27  
28      LRUMessageCache(int cacheSize) {
29          super((int) (cacheSize * (4.0f / 3)), 0.75f, true);
30          if (cacheSize < 1) {
31              throw new IllegalArgumentException("Cache size cannot be smaller than 1");
32          }
33          this.cacheSize = cacheSize;
34      }
35  
36      int getMessageCountAndThenIncrement(String msg) {
37          // don't insert null elements
38          if (msg == null) {
39              return 0;
40          }
41  
42          Integer i;
43          // LinkedHashMap is not LinkedHashMap. See also LBCLASSIC-255
44          synchronized (this) {
45              i = super.get(msg);
46              if (i == null) {
47                  i = 0;
48              } else {
49                  i = i + 1;
50              }
51              super.put(msg, i);
52          }
53          return i;
54      }
55  
56      // called indirectly by get() or put() which are already supposed to be
57      // called from within a synchronized block
58      protected boolean removeEldestEntry(Map.Entry<String, Integer> eldest) {
59          return (size() > cacheSize);
60      }
61  
62      @Override
63      synchronized public void clear() {
64          super.clear();
65      }
66  }