01: /*
02: * Licensed to the Apache Software Foundation (ASF) under one
03: * or more contributor license agreements. See the NOTICE file
04: * distributed with this work for additional information
05: * regarding copyright ownership. The ASF licenses this file
06: * to you under the Apache License, Version 2.0 (the
07: * "License"); you may not use this file except in compliance
08: * with the License. You may obtain a copy of the License at
09: *
10: * http://www.apache.org/licenses/LICENSE-2.0
11: *
12: * Unless required by applicable law or agreed to in writing,
13: * software distributed under the License is distributed on an
14: * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15: * KIND, either express or implied. See the License for the
16: * specific language governing permissions and limitations
17: * under the License.
18: */
19: package org.apache.openjpa.lib.util;
20:
21: import java.io.IOException;
22: import java.io.ObjectInputStream;
23: import java.io.ObjectOutputStream;
24: import java.util.Map;
25:
26: /**
27: * Extension of the commons <code>LRUMap</code> that can change its
28: * maximum size.
29: *
30: * @author Abe White
31: * @nojavadoc
32: */
33: public class LRUMap extends org.apache.commons.collections.map.LRUMap
34: implements SizedMap {
35:
36: private int _max = -1;
37:
38: public LRUMap() {
39: }
40:
41: public LRUMap(int maxSize) {
42: super (maxSize);
43: }
44:
45: public LRUMap(int maxSize, float loadFactor) {
46: super (maxSize, loadFactor);
47: }
48:
49: public LRUMap(Map map) {
50: super (map);
51: }
52:
53: public int getMaxSize() {
54: return maxSize();
55: }
56:
57: public void setMaxSize(int max) {
58: if (max < 0)
59: throw new IllegalArgumentException(String.valueOf(max));
60: _max = max;
61:
62: Object key;
63: while (size() > _max) {
64: key = lastKey();
65: overflowRemoved(key, remove(key));
66: }
67: }
68:
69: public void overflowRemoved(Object key, Object value) {
70: }
71:
72: public int maxSize() {
73: return (_max == -1) ? super .maxSize() : _max;
74: }
75:
76: public boolean isFull() {
77: return (_max == -1) ? super .isFull() : size() >= _max;
78: }
79:
80: protected boolean removeLRU(LinkEntry entry) {
81: overflowRemoved(entry.getKey(), entry.getValue());
82: return super .removeLRU(entry);
83: }
84:
85: protected void doWriteObject(ObjectOutputStream out)
86: throws IOException {
87: out.writeInt(_max);
88: super .doWriteObject(out);
89: }
90:
91: protected void doReadObject(ObjectInputStream in)
92: throws IOException, ClassNotFoundException {
93: _max = in.readInt();
94: super.doReadObject(in);
95: }
96: }
|