File D:\maven-qcr-plugin-testsunitaires\qcr4java\h2-1.3.170-sources\target\site\qc\lecode\util\SmallMap.java.html

1 /*
2 * Copyright 2004-2011 H2 Group. Multiple-Licensed under the H2 License,
3 * Version 1.0, and under the Eclipse Public License, Version 1.0
4 * (http://h2database.com/html/license.html).
5 * Initial Developer: H2 Group
6 */
7 package org.h2.util;
8
9 import java.util.HashMap;
10 import java.util.Iterator;
11
12 import org.h2.constant.ErrorCode;
13 import org.h2.message.DbException;
14
15 /**
16 * A simple hash table with an optimization for the last recently used object.
17 */
18 public class SmallMap {
19
20 private final HashMap<Integer, Object> map = New.hashMap();
21 private Object cache;
22 private int cacheId;
23 private int lastId;
24 private final int maxElements;
25
26 /**
27 * Create a map with the given maximum number of entries.
28 *
29 * @param maxElements the maximum number of entries
30 */
31 public SmallMap(int maxElements) {
32 this.maxElements = maxElements;
33 }
34
35 /**
36 * Add an object to the map. If the size of the map is larger than twice the
37 * maximum size, objects with a low id are removed.
38 *
39 * @param id the object id
40 * @param o the object
41 * @return the id
42 */
43 public int addObject(int id, Object o) {
44 if (map.size() > maxElements * 2) {
45 Iterator<Integer> it = map.keySet().iterator();
46 while (it.hasNext()) {
47 Integer k = it.next();
48 if (k.intValue() + maxElements < lastId) {
49 it.remove();
50 }
51 }
52 }
53 if (id > lastId) {
54 lastId = id;
55 }
56 map.put(id, o);
57 cacheId = id;
58 cache = o;
59 return id;
60 }
61
62 /**
63 * Remove an object from the map.
64 *
65 * @param id the id of the object to remove
66 */
67 public void freeObject(int id) {
68 if (cacheId == id) {
69 cacheId = -1;
70 cache = null;
71 }
72 map.remove(id);
73 }
74
75 /**
76 * Get an object from the map if it is stored.
77 *
78 * @param id the id of the object
79 * @param ifAvailable only return it if available, otherwise return null
80 * @return the object or null
81 * @throws DbException if isAvailable is false and the object has not been
82 * found
83 */
84 public Object getObject(int id, boolean ifAvailable) {
85 if (id == cacheId) {
86 return cache;
87 }
88 Object obj = map.get(id);
89 if (obj == null && !ifAvailable) {
90 throw DbException.get(ErrorCode.OBJECT_CLOSED);
91 }
92 return obj;
93 }
94
95 }
96