-
Notifications
You must be signed in to change notification settings - Fork 60
Expand file tree
/
Copy pathGlobalRef.java
More file actions
392 lines (354 loc) · 12.4 KB
/
Copy pathGlobalRef.java
File metadata and controls
392 lines (354 loc) · 12.4 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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
/* Copyright (c) Jython Developers */
package org.python.modules._weakref;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.python.core.JyAttribute;
import org.python.core.Py;
import org.python.core.PyList;
import org.python.core.PyObject;
import org.python.core.PySystemState;
import org.python.util.Generic;
import org.python.modules.gc;
public class GlobalRef extends WeakReference<PyObject> {
/**
* This reference's hashCode: The {@code System.identityHashCode} of the referent.
* Only used internally.
*/
private int hashCode;
/**
* The public hashCode for the Python AbstractReference wrapper. Derived from the
* referent's hashCode.
*/
private int pythonHashCode;
/** Whether {@link #pythonHashCode} was already determined. */
private boolean havePythonHashCode;
/**
* This boolean is set {@code true} when the callback is processed.
* If the reference is cleared it might potentially be restored until
* this boolean is set true. If weak reference restoring is activated (c.f.
* {@link gc#PRESERVE_WEAKREFS_ON_RESURRECTION}), {@link AbstractReference#get()}
* would block until a consistent state is reached (i.e. referent is
* non-{@code null} or {@code cleared == true}).
*
* @see gc#PRESERVE_WEAKREFS_ON_RESURRECTION
* @see AbstractReference#get()
*/
protected boolean cleared = false;
private List<WeakReference<AbstractReference>> references = new ArrayList<>();
private static ReferenceQueue<PyObject> referenceQueue = new ReferenceQueue<>();
private static Thread reaperThread;
private static ReentrantReadWriteLock reaperLock = new ReentrantReadWriteLock();
private static ConcurrentMap<GlobalRef, GlobalRef> objects = Generic.concurrentMap();
private static List<GlobalRef> delayedCallbacks;
public GlobalRef(PyObject object) {
super(object, referenceQueue);
hashCode = System.identityHashCode(object);
}
public synchronized void add(AbstractReference ref) {
WeakReference<AbstractReference> r = new WeakReference<>(ref);
references.add(r);
}
private final AbstractReference getReferenceAt(int idx) {
WeakReference<AbstractReference> wref = references.get(idx);
return wref.get();
}
/**
* Search for a reusable reference. To be reused, it must be of the
* same class and it must not have a callback.
*/
synchronized AbstractReference find(Class<?> cls) {
for (int i = references.size() - 1; i >= 0; i--) {
AbstractReference r = getReferenceAt(i);
if (r == null) {
references.remove(i);
} else if (r.callback == null && r.getClass() == cls) {
return r;
}
}
return null;
}
/**
* Call each of the registered references.
*/
synchronized void call() {
if (!cleared) {
cleared = true;
for (int i = references.size() - 1; i >= 0; i--) {
AbstractReference r = getReferenceAt(i);
if (r == null) {
references.remove(i);
} else {
Thread pendingGet = (Thread) JyAttribute.getAttr(
r, JyAttribute.WEAKREF_PENDING_GET_ATTR);
if (pendingGet != null) {
pendingGet.interrupt();
}
r.call();
}
}
}
}
/**
* Call all callbacks that were enqueued via
* {@link #delayedCallback(GlobalRef)} method.
*
* @see #delayedCallback(GlobalRef)
*/
public static void processDelayedCallbacks() {
if (delayedCallbacks != null) {
synchronized (delayedCallbacks) {
for (GlobalRef gref: delayedCallbacks) {
gref.call();
}
delayedCallbacks.clear();
}
}
}
/**
* Stores the callback for later processing. This is needed if
* weak reference restoration (c.f.
* {@link gc#PRESERVE_WEAKREFS_ON_RESURRECTION})
* is active. In this case the callback is delayed until it was
* determined whether a resurrection restored the reference.
*
* @see gc#PRESERVE_WEAKREFS_ON_RESURRECTION
*/
private static void delayedCallback(GlobalRef cl) {
if (delayedCallbacks == null) {
delayedCallbacks = new ArrayList<>();
}
synchronized (delayedCallbacks) {
delayedCallbacks.add(cl);
}
}
public static boolean hasDelayedCallbacks() {
return delayedCallbacks != null && !delayedCallbacks.isEmpty();
}
synchronized public int count() {
for (int i = references.size() - 1; i >= 0; i--) {
AbstractReference r = getReferenceAt(i);
if (r == null) {
references.remove(i);
}
}
return references.size();
}
synchronized public PyList refs() {
List<AbstractReference> list = new ArrayList<>();
for (int i = references.size() - 1; i >= 0; i--) {
AbstractReference r = getReferenceAt(i);
if (r == null) {
references.remove(i);
} else {
list.add(r);
}
}
return new PyList(list);
}
/**
* Create a new tracked {@code GlobalRef}.
*
* @param object a {@link org.python.core.PyObject} to reference
* @return a new tracked {@code GlobalRef}
*/
public static GlobalRef newInstance(PyObject object) {
createReaperThreadIfAbsent();
GlobalRef newRef = new GlobalRef(object);
GlobalRef ref = objects.putIfAbsent(newRef, newRef);
if (ref == null) {
ref = newRef;
JyAttribute.setAttr(object, JyAttribute.WEAK_REF_ATTR, ref);
} else {
// We clear the not-needed Global ref so that it won't
// pop up in ref-reaper thread's activity.
newRef.clear();
newRef.cleared = true;
}
return ref;
}
/**
* Restores this weak reference to its former referent.
* This actually means that a fresh {@code GlobalRef} is created
* and inserted into all adjacent
* {@link org.python.modules._weakref.AbstractReference}s. The
* current {@code GlobalRef} is disbanded.
* If the given {@link org.python.core.PyObject} is not the former
* referent of this weak reference, an
* {@link java.lang.IllegalArgumentException} is thrown.
*
* @throws java.lang.IllegalArgumentException if {@code formerReferent} is not
* the actual former referent.
*/
public void restore(PyObject formerReferent) {
if (JyAttribute.getAttr(formerReferent, JyAttribute.WEAK_REF_ATTR) != this) {
throw new IllegalArgumentException(
"Argument is not former referent of this GlobalRef.");
}
if (delayedCallbacks != null) {
synchronized (delayedCallbacks) {
delayedCallbacks.remove(this);
}
}
clear();
createReaperThreadIfAbsent();
GlobalRef restore = new GlobalRef(formerReferent);
restore.references = references;
objects.remove(this);
objects.put(restore, restore);
AbstractReference aref;
for (int i = references.size() - 1; i >= 0; i--) {
aref = getReferenceAt(i);
if (aref == null) {
references.remove(i);
} else {
aref.gref = restore;
Thread pendingGet = (Thread) JyAttribute.getAttr(
aref, JyAttribute.WEAKREF_PENDING_GET_ATTR);
if (pendingGet != null) {
pendingGet.interrupt();
}
}
}
}
private static void createReaperThreadIfAbsent() {
reaperLock.readLock().lock();
try {
if (reaperThread == null || !reaperThread.isAlive()) {
reaperLock.readLock().unlock();
reaperLock.writeLock().lock();
if (reaperThread == null || !reaperThread.isAlive()) {
try {
initReaperThread();
} finally {
reaperLock.readLock().lock();
reaperLock.writeLock().unlock();
}
}
}
} finally {
reaperLock.readLock().unlock();
}
}
/**
* Return the number of references to the specified
* {@link org.python.core.PyObject}.
*
* @param object a PyObject
* @return an int reference count
*/
public static int getCount(PyObject object) {
GlobalRef ref = objects.get(new GlobalRef(object));
return ref == null ? 0 : ref.count();
}
/**
* Return a list of references to the specified
* {@link org.python.core.PyObject}.
*
* @param object a {@link org.python.core.PyObject}
* @return a {@link org.python.core.PyList} of references. May be empty.
*/
public static PyList getRefs(PyObject object) {
GlobalRef ref = objects.get(new GlobalRef(object));
return ref == null ? new PyList() : ref.refs();
}
/**
* Allow {@code GlobalRef}s to be used as hashtable-keys.
*/
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof GlobalRef)) {
return false;
}
Object t = this.get();
Object u = ((GlobalRef)o).get();
if ((t == null) || (u == null)) {
return false;
}
if (t == u) {
return true;
}
// Don't consult the objects' equals (__eq__) method, it can't be trusted
return false;
}
/**
* Allows {@code GlobalRef} to be used as hashtable-keys.
*
* @return a hashCode {@code int}-value
*/
public int hashCode() {
return hashCode;
}
/**
* The publicly used {@code hashCode}, for the
* {@link org.python.modules._weakref.AbstractReference}
* wrapper.
*
* @return a hashCode {@code int}-value
*/
public int pythonHashCode() {
if (havePythonHashCode) {
return pythonHashCode;
}
Object referent = get();
if (referent == null) {
throw Py.TypeError("weak object has gone away");
}
pythonHashCode = referent.hashCode();
havePythonHashCode = true;
return pythonHashCode;
}
private static void initReaperThread() {
RefReaper reaper = new RefReaper();
PySystemState systemState = Py.getSystemState();
systemState.registerCloser(reaper);
reaperThread = new Thread(reaper, "weakref reaper");
reaperThread.setDaemon(true);
reaperThread.start();
}
private static class RefReaper implements Runnable, Callable<Void> {
private volatile boolean exit = false;
private Thread thread;
public void collect() throws InterruptedException {
GlobalRef gr = (GlobalRef) referenceQueue.remove();
if ((gc.getJythonGCFlags() & gc.PRESERVE_WEAKREFS_ON_RESURRECTION) == 0) {
gr.call();
} else {
delayedCallback(gr);
}
objects.remove(gr);
gr = null;
}
@Override
public void run() {
// Store the actual reaper thread so that when PySystemState.cleanup()
// is called this thread can be interrupted and die.
this.thread = Thread.currentThread();
while (true) {
try {
collect();
} catch (InterruptedException exc) {
// Is cleanup time so break out and die.
if (exit) {
break;
}
}
}
}
@Override
public Void call() throws Exception {
this.exit = true;
if (thread != null && thread.isAlive()) {
this.thread.interrupt();
this.thread = null;
}
return null;
}
}
}