-
Notifications
You must be signed in to change notification settings - Fork 226
Expand file tree
/
Copy pathIdImpl.java
More file actions
104 lines (83 loc) · 2.72 KB
/
IdImpl.java
File metadata and controls
104 lines (83 loc) · 2.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package org.python.core;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.util.Map;
import org.python.util.Generic;
public class IdImpl {
public static class WeakIdentityMap {
private transient ReferenceQueue<Object> idKeys = new ReferenceQueue<Object>();
private Map<WeakIdKey, Object> objHashcodeToPyId = Generic.map();
@SuppressWarnings("element-type-mismatch")
private void cleanup() {
Object k;
while ((k = idKeys.poll()) != null) {
objHashcodeToPyId.remove(k);
}
}
private class WeakIdKey extends WeakReference<Object> {
private final int hashcode;
WeakIdKey(Object obj) {
super(obj, idKeys);
hashcode = System.identityHashCode(obj);
}
@Override
public int hashCode() {
return hashcode;
}
@Override
public boolean equals(Object other) {
Object obj = get();
if (obj != null) {
return obj == ((WeakIdKey)other).get();
} else {
return this == other;
}
}
}
// Used by test_jy_internals
public int _internal_map_size() {
return objHashcodeToPyId.size();
}
public void put(Object key, Object val) {
cleanup();
objHashcodeToPyId.put(new WeakIdKey(key), val);
}
public Object get(Object key) {
cleanup();
return objHashcodeToPyId.get(new WeakIdKey(key));
}
public void remove(Object key) {
cleanup();
objHashcodeToPyId.remove(new WeakIdKey(key));
}
}
private WeakIdentityMap idMap = new WeakIdentityMap();
private long sequentialId;
public synchronized long id(PyObject o) {
Object id = JyAttribute.getAttr(o, JyAttribute.PY_ID_ATTR);
if (id != null) {
return ((Long) id).longValue();
}
Object javaProxy = o.getJavaProxy();
long result;
if (javaProxy != null) {
result = java_obj_id(javaProxy);
} else {
result = java_obj_id(o);
}
JyAttribute.setAttr(o, JyAttribute.PY_ID_ATTR, result);
return result;
}
public String idstr(PyObject o) {
return String.format("0x%x", id(o));
}
public synchronized long java_obj_id(Object o) {
Long cand = (Long)idMap.get(o);
if (cand == null) {
long new_id = ++sequentialId;
idMap.put(o, new_id);
return new_id;
}
return cand.longValue();
}
}