LRUMap.java

  1. /*
  2.  * Copyright (C) 2018, Konrad Windszus <konrad_w@gmx.de> and others
  3.  *
  4.  * This program and the accompanying materials are made available under the
  5.  * terms of the Eclipse Distribution License v. 1.0 which is available at
  6.  * https://www.eclipse.org/org/documents/edl-v10.php.
  7.  *
  8.  * SPDX-License-Identifier: BSD-3-Clause
  9.  */
  10. package org.eclipse.jgit.util;

  11. import java.util.LinkedHashMap;

  12. /**
  13.  * Map with only up to n entries. If a new entry is added so that the map
  14.  * contains more than those n entries the least-recently used entry is removed
  15.  * from the map.
  16.  *
  17.  * @param <K>
  18.  *            the type of keys maintained by this map
  19.  * @param <V>
  20.  *            the type of mapped values
  21.  *
  22.  * @since 5.4
  23.  */
  24. public class LRUMap<K, V> extends LinkedHashMap<K, V> {

  25.     private static final long serialVersionUID = 4329609127403759486L;

  26.     private final int limit;

  27.     /**
  28.      * Constructs an empty map which may contain at most the given amount of
  29.      * entries.
  30.      *
  31.      * @param initialCapacity
  32.      *            the initial capacity
  33.      * @param limit
  34.      *            the number of entries the map should have at most
  35.      */
  36.     public LRUMap(int initialCapacity, int limit) {
  37.         super(initialCapacity, 0.75f, true);
  38.         this.limit = limit;
  39.     }

  40.     @Override
  41.     protected boolean removeEldestEntry(java.util.Map.Entry<K, V> eldest) {
  42.         return size() > limit;
  43.     }
  44. }