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
21   * {@link #getMessageCountAndThenIncrement} method. Other methods inherited via
22   * LinkedHashMap are not thread safe.
23   */
24  class LRUMessageCache extends LinkedHashMap<String, Integer> {
25  
26      private static final long serialVersionUID = 1L;
27      final int cacheSize;
28  
29      LRUMessageCache(int cacheSize) {
30          super((int) (cacheSize * (4.0f / 3)), 0.75f, true);
31          if (cacheSize < 1) {
32              throw new IllegalArgumentException("Cache size cannot be smaller than 1");
33          }
34          this.cacheSize = cacheSize;
35      }
36  
37      int getMessageCountAndThenIncrement(String msg) {
38          // don't insert null elements
39          if (msg == null) {
40              return 0;
41          }
42  
43          Integer i;
44          // LinkedHashMap is not LinkedHashMap. See also LBCLASSIC-255
45          synchronized (this) {
46              i = super.get(msg);
47              if (i == null) {
48                  i = 0;
49              } else {
50                  i = i + 1;
51              }
52              super.put(msg, i);
53          }
54          return i;
55      }
56  
57      // called indirectly by get() or put() which are already supposed to be
58      // called from within a synchronized block
59      protected boolean removeEldestEntry(Map.Entry<String, Integer> eldest) {
60          return (size() > cacheSize);
61      }
62  
63      @Override
64      synchronized public void clear() {
65          super.clear();
66      }
67  }