File D:\maven-qcr-plugin-testsunitaires\qcr4java\h2-1.3.170-sources\target\site\qc\lecode\util\SoftHashMap.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.lang.ref.Reference;
10 import java.lang.ref.ReferenceQueue;
11 import java.lang.ref.SoftReference;
12 import java.util.AbstractMap;
13 import java.util.Map;
14 import java.util.Set;
15
16 /**
17 * Map which stores items using SoftReference. Items can be garbage collected
18 * and removed. It is not a general purpose cache, as it doesn't implement some
19 * methods, and others not according to the map definition, to improve speed.
20 *
21 * @param <K> the key type
22 * @param <V> the value type
23 */
24 public class SoftHashMap<K, V> extends AbstractMap<K, V> {
25
26 private final Map<K, SoftValue<V>> map;
27 private final ReferenceQueue<V> queue = new ReferenceQueue<V>();
28
29 public SoftHashMap() {
30 map = New.hashMap();
31 }
32
33 @SuppressWarnings("unchecked")
34 private void processQueue() {
35 while (true) {
36 Reference<? extends V> o = queue.poll();
37 if (o == null) {
38 return;
39 }
40 SoftValue<V> k = (SoftValue<V>) o;
41 Object key = k.key;
42 map.remove(key);
43 }
44 }
45
46 public V get(Object key) {
47 processQueue();
48 SoftReference<V> o = map.get(key);
49 if (o == null) {
50 return null;
51 }
52 return o.get();
53 }
54
55 /**
56 * Store the object. The return value of this method is null or a SoftReference.
57 *
58 * @param key the key
59 * @param value the value
60 * @return null or the old object.
61 */
62 public V put(K key, V value) {
63 processQueue();
64 SoftValue<V> old = map.put(key, new SoftValue<V>(value, queue, key));
65 return old == null ? null : old.get();
66 }
67
68 /**
69 * Remove an object.
70 *
71 * @param key the key
72 * @return null or the old object
73 */
74 public V remove(Object key) {
75 processQueue();
76 SoftReference<V> ref = map.remove(key);
77 return ref == null ? null : ref.get();
78 }
79
80 public void clear() {
81 processQueue();
82 map.clear();
83 }
84
85 public Set<Entry<K, V>> entrySet() {
86 throw new UnsupportedOperationException();
87 }
88
89 /**
90 * A soft reference that has a hard reference to the key.
91 */
92 private static class SoftValue<T> extends SoftReference<T> {
93 final Object key;
94
95 public SoftValue(T ref, ReferenceQueue<T> q, Object key) {
96 super(ref, q);
97 this.key = key;
98 }
99
100 }
101
102 }
103