View Javadoc

1   /*
2    * Copyright 2004-2010 the Seasar Foundation and the Others.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
13   * either express or implied. See the License for the specific language
14   * governing permissions and limitations under the License.
15   */
16  
17  package org.seasar.cubby.internal.util;
18  
19  import java.util.LinkedHashMap;
20  import java.util.Map;
21  
22  /**
23   * LRU (Least Recently Used) アルゴリズムによって最近最も使われなかったエントリを削除することによって、一定のサイズを保つ
24   * {@link Map} です。
25   * <p>
26   * 最近最も使われなかったもの
27   * </p>
28   * 
29   * @param <K>
30   *            キーの型
31   * @param <V>
32   *            値の型
33   * @author baba
34   */
35  public class LruHashMap<K, V> extends LinkedHashMap<K, V> {
36  
37  	/** シリアルバージョン UID。 */
38  	private static final long serialVersionUID = 1L;
39  
40  	/** デフォルトの初期容量です。 */
41  	protected static final int DEFAULT_INITIAL_CAPACITY = 16;
42  
43  	/** デフォルトのロードファクタです。 */
44  	protected static final float DEFAULT_LOAD_FACTOR = 0.75f;
45  
46  	/**
47  	 * 上限サイズです。
48  	 */
49  	protected int limitSize;
50  
51  	/**
52  	 * {@link LruHashMap} を作成します。
53  	 * 
54  	 * @param limitSize
55  	 *            上限サイズ
56  	 */
57  	public LruHashMap(final int limitSize) {
58  		this(limitSize, DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
59  	}
60  
61  	/**
62  	 * {@link LruHashMap}を作成します。
63  	 * 
64  	 * @param limitSize
65  	 * @param initialCapacity
66  	 * @param loadFactor
67  	 */
68  	public LruHashMap(final int limitSize, final int initialCapacity,
69  			final float loadFactor) {
70  		super(initialCapacity, loadFactor, true);
71  		this.limitSize = limitSize;
72  	}
73  
74  	/**
75  	 * 上限サイズを返します。
76  	 * 
77  	 * @return 上限サイズ
78  	 */
79  	public int getLimitSize() {
80  		return limitSize;
81  	}
82  
83  	/**
84  	 * {@inheritDoc}
85  	 */
86  	@Override
87  	protected boolean removeEldestEntry(final Map.Entry<K, V> entry) {
88  		return this.size() > limitSize;
89  	}
90  
91  }