01: package org.python.core;
02:
03: import java.lang.ref.WeakReference;
04: import java.lang.ref.ReferenceQueue;
05: import java.util.HashMap;
06:
07: public class IdImpl2 extends IdImpl {
08:
09: public static class WeakIdentityMap {
10:
11: private ReferenceQueue refqueue = new ReferenceQueue();
12: private HashMap hashmap = new HashMap();
13:
14: private void cleanup() {
15: Object k;
16: while ((k = this .refqueue.poll()) != null) {
17: this .hashmap.remove(k);
18: }
19: }
20:
21: private class WeakIdKey extends WeakReference {
22: private int hashcode;
23:
24: WeakIdKey(Object obj) {
25: super (obj, WeakIdentityMap.this .refqueue);
26: this .hashcode = System.identityHashCode(obj);
27: }
28:
29: public int hashCode() {
30: return this .hashcode;
31: }
32:
33: public boolean equals(Object other) {
34: Object obj = this .get();
35: if (obj != null) {
36: return obj == ((WeakIdKey) other).get();
37: } else {
38: return this == other;
39: }
40: }
41: }
42:
43: public int _internal_map_size() {
44: return this .hashmap.size();
45: }
46:
47: public void put(Object key, Object val) {
48: cleanup();
49: this .hashmap.put(new WeakIdKey(key), val);
50: }
51:
52: public Object get(Object key) {
53: cleanup();
54: return this .hashmap.get(new WeakIdKey(key));
55: }
56:
57: public void remove(Object key) {
58: cleanup();
59: this .hashmap.remove(new WeakIdKey(key));
60: }
61:
62: }
63:
64: private WeakIdentityMap id_map = new WeakIdentityMap();
65: private long sequential_id = 0;
66:
67: public long id(PyObject o) {
68: if (o instanceof PyJavaInstance) {
69: return java_obj_id(((PyJavaInstance) o).javaProxy);
70: } else {
71: return java_obj_id(o);
72: }
73: }
74:
75: // XXX maybe should display both this id and identityHashCode
76: // XXX preserve the old "at ###" style?
77: public String idstr(PyObject o) {
78: return Long.toString(id(o));
79: }
80:
81: public synchronized long java_obj_id(Object o) {
82: Long cand = (Long) this .id_map.get(o);
83: if (cand == null) {
84: this .sequential_id++;
85: long new_id = this .sequential_id;
86: this .id_map.put(o, new Long(new_id));
87: return new_id;
88: }
89: return cand.longValue();
90: }
91:
92: }
|