View Javadoc
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  
12  import java.util.LinkedHashMap;
13  
14  /**
15   * Map with only up to n entries. If a new entry is added so that the map
16   * contains more than those n entries the least-recently used entry is removed
17   * from the map.
18   *
19   * @param <K>
20   *            the type of keys maintained by this map
21   * @param <V>
22   *            the type of mapped values
23   *
24   * @since 5.4
25   */
26  public class LRUMap<K, V> extends LinkedHashMap<K, V> {
27  
28  	private static final long serialVersionUID = 4329609127403759486L;
29  
30  	private final int limit;
31  
32  	/**
33  	 * Constructs an empty map which may contain at most the given amount of
34  	 * entries.
35  	 *
36  	 * @param initialCapacity
37  	 *            the initial capacity
38  	 * @param limit
39  	 *            the number of entries the map should have at most
40  	 */
41  	public LRUMap(int initialCapacity, int limit) {
42  		super(initialCapacity, 0.75f, true);
43  		this.limit = limit;
44  	}
45  
46  	@Override
47  	protected boolean removeEldestEntry(java.util.Map.Entry<K, V> eldest) {
48  		return size() > limit;
49  	}
50  }