01: /*
02: * Copyright 2006 Davide Deidda
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
10: * Unless required by applicable law or agreed to in writing, software
11: * distributed under the License is distributed on an "AS IS" BASIS,
12: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13: * See the License for the specific language governing permissions and
14: * limitations under the License.
15: */
16:
17: /*
18: * ReferenceMarker.java
19: *
20: * Created on 9 aprile 2005, 18.30
21: */
22:
23: package it.biobytes.ammentos.util;
24:
25: import java.util.*;
26: import java.util.concurrent.*;
27: import java.lang.ref.*;
28: import java.util.logging.*;
29:
30: /**
31: * Marks references of the provided objects. This class mantains a collections
32: * of marked objects, whithout preventing them from being garbage collected.
33: * This special behavior allows the system to keeping trace of loaded objects.
34: *
35: * @author Davide Deidda
36: */
37: public class ReferenceMarker {
38: /** A identity hashmap is used to ensure that equal objects will be not
39: stored at the same key
40: **/
41: private HashMap<Integer, MarkedWeakReference> m_references;
42: private final ReferenceQueue m_referenceQueue;
43: private Logger m_logger = Logger.getLogger("ammentos");
44:
45: private class MarkedWeakReference extends WeakReference {
46: private int identityObjHashCode;
47:
48: public MarkedWeakReference(Object obj, ReferenceQueue q) {
49: super (obj, q);
50: identityObjHashCode = System.identityHashCode(obj);
51: }
52: }
53:
54: /** Creates a new instance of ReferenceMarker */
55: public ReferenceMarker() {
56: m_references = new HashMap<Integer, MarkedWeakReference>();
57: m_referenceQueue = new ReferenceQueue();
58: }
59:
60: public void mark(Object obj) {
61: expungeStaleEntries();
62: m_references.put(System.identityHashCode(obj),
63: new MarkedWeakReference(obj, m_referenceQueue));
64: }
65:
66: public void unmark(Object obj) {
67: expungeStaleEntries();
68: m_references.remove(System.identityHashCode(obj));
69: }
70:
71: public boolean isMarked(Object obj) {
72: expungeStaleEntries();
73: return (m_references.get(System.identityHashCode(obj)) != null);
74: }
75:
76: protected void expungeStaleEntries() {
77: MarkedWeakReference ref = null;
78: while ((ref = (MarkedWeakReference) m_referenceQueue.poll()) != null) {
79: MarkedWeakReference r = m_references
80: .remove(ref.identityObjHashCode);
81: m_logger.info("Map size: " + m_references.size());
82: }
83: }
84: }
|