01: /*
02: * Copyright 2004-2008 H2 Group. Licensed under the H2 License, Version 1.0
03: * (http://h2database.com/html/license.html).
04: * Initial Developer: H2 Group
05: */
06: package org.h2.util;
07:
08: import java.sql.SQLException;
09: import java.util.HashMap;
10: import java.util.Iterator;
11:
12: import org.h2.constant.ErrorCode;
13: import org.h2.message.Message;
14:
15: /**
16: * A simple hash table with an optimization for the last recently used object.
17: */
18: public class SmallMap {
19: private HashMap map = new HashMap();
20: private Object cache;
21: private int cacheId;
22: private int lastId;
23: private int maxElements;
24:
25: public SmallMap(int maxElements) {
26: this .maxElements = maxElements;
27: }
28:
29: public int addObject(int id, Object o) {
30: if (map.size() > maxElements * 2) {
31: Iterator it = map.keySet().iterator();
32: while (it.hasNext()) {
33: Integer k = (Integer) it.next();
34: if (k.intValue() + maxElements < lastId) {
35: it.remove();
36: }
37: }
38: }
39: if (id > lastId) {
40: lastId = id;
41: }
42: map.put(ObjectUtils.getInteger(id), o);
43: cacheId = id;
44: cache = o;
45: return id;
46: }
47:
48: public void freeObject(int id) {
49: if (cacheId == id) {
50: cacheId = -1;
51: cache = null;
52: }
53: map.remove(ObjectUtils.getInteger(id));
54: }
55:
56: public Object getObject(int id, boolean ifAvailable)
57: throws SQLException {
58: if (id == cacheId) {
59: return cache;
60: }
61: Object obj = map.get(ObjectUtils.getInteger(id));
62: if (obj == null && !ifAvailable) {
63: throw Message.getSQLException(ErrorCode.OBJECT_CLOSED);
64: }
65: return obj;
66: }
67:
68: }
|