| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
package org.jpype.ref; |
| 17 |
|
| 18 |
import java.util.ArrayList; |
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
public class JPypeReferenceSet |
| 25 |
{ |
| 26 |
|
| 27 |
static final int SIZE = 256; |
| 28 |
ArrayList<Pool> pools = new ArrayList<>(); |
| 29 |
Pool current; |
| 30 |
private int items; |
| 31 |
|
| 32 |
JPypeReferenceSet() |
| 33 |
{ |
| 34 |
} |
| 35 |
|
| 36 |
int size() |
| 37 |
{ |
| 38 |
return items; |
| 39 |
} |
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
|
| 46 |
|
| 47 |
|
| 48 |
synchronized void add(JPypeReference ref) |
| 49 |
{ |
| 50 |
if (ref.cleanup == 0) |
| 51 |
return; |
| 52 |
|
| 53 |
this.items++; |
| 54 |
if (current == null) |
| 55 |
{ |
| 56 |
current = new Pool(pools.size()); |
| 57 |
pools.add(current); |
| 58 |
} |
| 59 |
|
| 60 |
if (current.add(ref)) |
| 61 |
{ |
| 62 |
|
| 63 |
current = null; |
| 64 |
|
| 65 |
|
| 66 |
for (Pool pool : pools) |
| 67 |
{ |
| 68 |
if (pool.tail < SIZE) |
| 69 |
{ |
| 70 |
current = pool; |
| 71 |
return; |
| 72 |
} |
| 73 |
} |
| 74 |
} |
| 75 |
} |
| 76 |
|
| 77 |
|
| 78 |
|
| 79 |
|
| 80 |
|
| 81 |
|
| 82 |
synchronized void remove(JPypeReference ref) |
| 83 |
{ |
| 84 |
if (ref.cleanup == 0) |
| 85 |
return; |
| 86 |
pools.get(ref.pool).remove(ref); |
| 87 |
this.items--; |
| 88 |
ref.cleanup = 0; |
| 89 |
ref.pool = -1; |
| 90 |
} |
| 91 |
|
| 92 |
|
| 93 |
|
| 94 |
|
| 95 |
|
| 96 |
|
| 97 |
|
| 98 |
|
| 99 |
void flush() |
| 100 |
{ |
| 101 |
for (Pool pool : pools) |
| 102 |
{ |
| 103 |
for (int i = 0; i < pool.tail; ++i) |
| 104 |
{ |
| 105 |
JPypeReference ref = pool.entries[i]; |
| 106 |
long hostRef = ref.hostReference; |
| 107 |
long cleanup = ref.cleanup; |
| 108 |
|
| 109 |
|
| 110 |
|
| 111 |
if (cleanup == 0) |
| 112 |
continue; |
| 113 |
ref.cleanup = 0; |
| 114 |
JPypeReferenceNative.removeHostReference(hostRef, cleanup); |
| 115 |
} |
| 116 |
pool.tail = 0; |
| 117 |
} |
| 118 |
} |
| 119 |
|
| 120 |
|
| 121 |
static class Pool |
| 122 |
{ |
| 123 |
|
| 124 |
JPypeReference[] entries = new JPypeReference[SIZE]; |
| 125 |
int tail; |
| 126 |
int id; |
| 127 |
|
| 128 |
Pool(int id) |
| 129 |
{ |
| 130 |
this.id = id; |
| 131 |
} |
| 132 |
|
| 133 |
boolean add(JPypeReference ref) |
| 134 |
{ |
| 135 |
ref.pool = id; |
| 136 |
ref.index = tail; |
| 137 |
entries[tail++] = ref; |
| 138 |
return (tail == entries.length); |
| 139 |
} |
| 140 |
|
| 141 |
void remove(JPypeReference ref) |
| 142 |
{ |
| 143 |
entries[ref.index] = entries[--tail]; |
| 144 |
entries[ref.index].index = ref.index; |
| 145 |
} |
| 146 |
} |
| 147 |
|
| 148 |
} |