blob: 41e1d79f40e8f1ea7305193b9d16676b8a7134d0 (
plain) (
blame)
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
|
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jdisc.refcount;
import com.yahoo.jdisc.ResourceReference;
import java.util.HashMap;
import java.util.Map;
/**
* Does reference counting by putting a unique key together with optional context in map
* Used if system property jdisc.debug.resources=simple/true
*
* @author baldersheim
*/
public class DebugReferencesByContextMap implements References {
private final Map<Object, Object> contextMap = new HashMap<>();
private final DestructableResource resource;
private final Reference initialReference;
private long contextId = 1;
public DebugReferencesByContextMap(DestructableResource resource, Object context) {
this.resource = resource;
Long key = 0L;
initialReference = new Reference(this, key);
contextMap.put(key, context);
}
@Override
public void release() {
initialReference.close();
}
@Override
public int referenceCount() {
synchronized (contextMap) { return contextMap.size(); }
}
@Override
public ResourceReference refer(Object context) {
synchronized (contextMap) {
if (contextMap.isEmpty()) {
throw new IllegalStateException("Object is already destroyed, no more new references may be created."
+ " State={ " + currentState() + " }");
}
Long key = contextId++;
contextMap.put(key, context != null ? context : key);
return new Reference(this, key);
}
}
private void removeRef(Long key) {
synchronized (contextMap) {
contextMap.remove(key);
if (contextMap.isEmpty()) {
resource.close();
}
}
}
@Override
public String currentState() {
synchronized (contextMap) {
return contextMap.toString();
}
}
private static class Reference extends CloseableOnce {
private final DebugReferencesByContextMap references;
private final Long key;
Reference(DebugReferencesByContextMap references, Long key) {
this.references = references;
this.key = key;
}
@Override final void onClose() { references.removeRef(key); }
@Override
final References getReferences() { return references; }
}
}
|