分享一个LRUMap的实现――来自apache common-collections框架 (五)

2014-11-24 08:12:18 · 作者: · 浏览: 6
eader) {
192: modCount++;
193: // remove
194: entry.before.after = entry.after;
195: entry.after.before = entry.before;
196: // add first
197: entry.after = header;
198: entry.before = header.before;
199: header.before.after = entry;
200: header.before = entry;
201: } else if (entry == header) {
202: throw new IllegalStateException("Can't move header to MRU" +
203: " (please report this to commons-dev@jakarta.apache.org)");
204: }
205: }
206:
207: /**
208: * Updates an existing key-value mapping.
209: *


210: * This implementation moves the updated entry to the top of the list
211: * using {@link #moveToMRU(AbstractLinkedMap.LinkEntry)}.
212: *
213: * @param entry the entry to update
214: * @param newValue the new value to store
215: */
216: protected void updateEntry(HashEntry entry, Object newValue) {
217: moveToMRU((LinkEntry) entry); // handles modCount
218: entry.setValue(newValue);
219: }
220:
221: /**
222: * Adds a new key-value mapping into this map.
223: *


224: * This implementation checks the LRU size and determines whether to
225: * discard an entry or not using {@link #removeLRU(AbstractLinkedMap.LinkEntry)}.
226: *


227: * From Commons Collections 3.1 this method uses {@link #isFull()} rather
228: * than accessing size and maxSize directly.
229: * It also handles the scanUntilRemovable functionality.
230: *
231: * @param hashIndex the index into the data array to store at
232: * @param hashCode the hash code of the key to add
233: * @param key the key to add
234: * @param value the value to add
235: */
236: protected void addMapping(int hashIndex, int hashCode, Object key, Object value) {
237: if (isFull()) {
238: LinkEntry reuse = header.after;
239: boolean removeLRUEntry = false;
240: if (scanUntilRemovable) {
241: while (reuse != header && reuse != null) {
242: if (removeLRU(reuse)) {
243: removeLRUEntry = true;
244: break;
245: }
246: reuse = reuse.after;
247: }
248: if (reuse == null) {
249: throw new IllegalStateException(
250: "Entry.after=null, header.after" + header.after + " header.before" + header.before +
251: " key=" + key + " value=" + value + " size=" + size + " maxSize=" + maxSize +
252: " Please check that your keys are immutable, and that you have used synchronization properly." +
253: " If so, then please report this to commons-dev@jakarta.apache.org as a bug.");
254: }
255: } else {
256: removeLRUEntry = removeLRU(reuse);
257: }
258:
259: if (removeLRUEntry) {
260: if (reuse == null) {
261: throw new IllegalStateException(
262: "reuse=null, header.after=" + header.after + " header.before" +