-
Notifications
You must be signed in to change notification settings - Fork 53
/
OperationContext.java
executable file
·362 lines (315 loc) · 12.8 KB
/
OperationContext.java
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
/*
* Copyright (c) 2015, 2024 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0, which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the
* Eclipse Public License v. 2.0 are satisfied: GNU General Public License,
* version 2 with the GNU Classpath Exception, which is available at
* https://www.gnu.org/software/classpath/license.html.
*
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/
package org.glassfish.hk2.extras.operation;
import java.lang.annotation.Annotation;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import org.glassfish.hk2.api.ActiveDescriptor;
import org.glassfish.hk2.api.Context;
import org.glassfish.hk2.api.ServiceHandle;
import org.glassfish.hk2.extras.operation.internal.OperationHandleImpl;
import org.glassfish.hk2.extras.operation.internal.SingleOperationManager;
import org.glassfish.hk2.utilities.reflection.Logger;
import org.jvnet.hk2.annotations.Contract;
/**
* The implementation of {@link Context} for an Operation.
* <p>
* An operation is defined as a unit of work that can
* be associated with one or more java threads, but where
* two operations of the same type may not be associated
* with the same thread at the same time. Examples of such
* an operation might be a RequestScope or a TenantRequesteOperation.
* An operation is a more general concept than the normal
* Java EE request scope, since it does not require a Java EE
* container
* <p>
* Users of this API generally create a {@link jakarta.inject.Scope} annotation
* and extend this class, implementing the {@link Context#getScope()}
* and making sure the parameterized type is the Scope annotation.
* The {@link jakarta.inject.Scope} annotation for an Operation is usually
* {@link org.glassfish.hk2.api.Proxiable} but does not have to be. As with all implementations
* of {@link Context} the subclass of this class must be in the {@link SingletonInjectsPerRequest}
* scope. The user code then uses the {@link OperationManager} and {@link OperationHandle}
* to start and stop Operations and to associate and dis-associate
* threads with Operations
* <p>
* Classes extending this class may also choose to override the method
* {@link Context#supportsNullCreation()} which returns false by default
*
* @author jwells
*/
@Contract
public abstract class OperationContext<T extends Annotation> implements Context<T> {
private SingleOperationManager<T> manager;
private final ReentrantLock lock = new ReentrantLock();
private final Condition condition = lock.newCondition();
private final HashMap<OperationHandleImpl<T>, LinkedHashMap<ActiveDescriptor<?>, Object>> operationMap =
new HashMap<OperationHandleImpl<T>, LinkedHashMap<ActiveDescriptor<?>, Object>>();
private final HashSet<ActiveDescriptor<?>> creating = new HashSet<ActiveDescriptor<?>>();
private final HashMap<Long, LinkedList<OperationHandleImpl<T>>> closingOperations = new HashMap<Long, LinkedList<OperationHandleImpl<T>>>();
private boolean shuttingDown = false;
/* (non-Javadoc)
* @see org.glassfish.hk2.api.Context#findOrCreate(org.glassfish.hk2.api.ActiveDescriptor, org.glassfish.hk2.api.ServiceHandle)
*/
@SuppressWarnings("unchecked")
@Override
public <U> U findOrCreate(ActiveDescriptor<U> activeDescriptor,
ServiceHandle<?> root) {
SingleOperationManager<T> localManager;
LinkedList<OperationHandleImpl<T>> closingOperationStack;
boolean closingOperation;
lock.lock();
try {
localManager = manager;
closingOperationStack = closingOperations.get(Thread.currentThread().getId());
closingOperation = (closingOperationStack != null && !closingOperationStack.isEmpty());
} finally {
lock.unlock();
}
if (localManager == null) {
throw new IllegalStateException("There is no manager for " +
getScope().getName() + " on thread " + Thread.currentThread().getId());
}
OperationHandleImpl<T> operation = localManager.getCurrentOperationOnThisThread();
if (operation == null) {
lock.lock();
try {
if (!closingOperation) {
throw new IllegalStateException("There is no current operation of type " +
getScope().getName() + " on thread " + Thread.currentThread().getId());
}
operation = closingOperationStack.get(0);
} finally {
lock.unlock();
}
}
LinkedHashMap<ActiveDescriptor<?>, Object> serviceMap;
lock.lock();
try {
serviceMap = operationMap.get(operation);
if (serviceMap == null) {
if (closingOperation || shuttingDown) {
throw new IllegalStateException("The operation " + operation.getIdentifier() +
" is closing. A new instance of " + activeDescriptor +
" cannot be created");
}
serviceMap = new LinkedHashMap<ActiveDescriptor<?>, Object>();
operationMap.put(operation, serviceMap);
}
Object retVal = serviceMap.get(activeDescriptor);
if (retVal != null) return (U) retVal;
if (supportsNullCreation() && serviceMap.containsKey(activeDescriptor)) {
return null;
}
if (closingOperation || shuttingDown) {
throw new IllegalStateException("The operation " + operation.getIdentifier() +
" is closing. A new instance of " + activeDescriptor +
" cannot be created after searching existing descriptors");
}
// retVal is null, and this is not an explicit null, so must actually do the creation
while (creating.contains(activeDescriptor)) {
try {
condition.await();
}
catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
retVal = serviceMap.get(activeDescriptor);
if (retVal != null) return (U) retVal;
if (supportsNullCreation() && serviceMap.containsKey(activeDescriptor)) {
return null;
}
// Not in creating, and not created. Create it ourselves
creating.add(activeDescriptor);
} finally {
lock.unlock();
}
Object retVal = null;
boolean success = false;
try {
retVal = activeDescriptor.create(root);
if (retVal == null && !supportsNullCreation()) {
throw new IllegalArgumentException("The operation for context " + getScope().getName() +
" does not support null creation, but descriptor " + activeDescriptor + " returned null");
}
success = true;
}
finally {
lock.lock();
try {
if (success) {
serviceMap.put(activeDescriptor, retVal);
}
creating.remove(activeDescriptor);
condition.signalAll();
} finally {
lock.unlock();
}
}
return (U) retVal;
}
/* (non-Javadoc)
* @see org.glassfish.hk2.api.Context#containsKey(org.glassfish.hk2.api.ActiveDescriptor)
*/
@Override
public boolean containsKey(ActiveDescriptor<?> descriptor) {
SingleOperationManager<T> localManager;
lock.lock();
try {
localManager = manager;
} finally {
lock.unlock();
}
if (localManager == null) return false;
OperationHandleImpl<T> operation = localManager.getCurrentOperationOnThisThread();
if (operation == null) return false;
lock.lock();
try {
HashMap<ActiveDescriptor<?>, Object> serviceMap;
serviceMap = operationMap.get(operation);
if (serviceMap == null) return false;
return serviceMap.containsKey(descriptor);
} finally {
lock.unlock();
}
}
/* (non-Javadoc)
* @see org.glassfish.hk2.api.Context#destroyOne(org.glassfish.hk2.api.ActiveDescriptor)
*/
@SuppressWarnings("unchecked")
@Override
public void destroyOne(ActiveDescriptor<?> descriptor) {
lock.lock();
try {
for (HashMap<ActiveDescriptor<?>, Object> serviceMap : operationMap.values()) {
Object killMe = serviceMap.remove(descriptor);
if (killMe == null) continue;
((ActiveDescriptor<Object>) descriptor).dispose(killMe);
}
} finally {
lock.unlock();
}
}
@SuppressWarnings("unchecked")
public void closeOperation(OperationHandleImpl<T> operation) {
long tid = Thread.currentThread().getId();
HashMap<ActiveDescriptor<?>, Object> serviceMap;
LinkedList<OperationHandleImpl<T>> stack;
lock.lock();
try {
stack = closingOperations.get(tid);
if (stack == null) {
stack = new LinkedList<OperationHandleImpl<T>>();
closingOperations.put(tid, stack);
}
stack.addFirst(operation);
serviceMap = operationMap.get(operation);
} finally {
lock.unlock();
}
try {
// Must be done outside of the lock
if (serviceMap == null) return;
// Reverses creation order
LinkedList<Map.Entry<ActiveDescriptor<?>, Object>> destructionList = new LinkedList<Map.Entry<ActiveDescriptor<?>, Object>>();
for (Map.Entry<ActiveDescriptor<?>, Object> entry : serviceMap.entrySet()) {
destructionList.addFirst(entry);
}
for (Map.Entry<ActiveDescriptor<?>, Object> entry : destructionList) {
ActiveDescriptor<Object> desc = (ActiveDescriptor<Object>) entry.getKey();
Object value = entry.getValue();
try {
desc.dispose(value);
}
catch (Throwable th) {
Logger.getLogger().debug(getClass().getName(), "closeOperation", th);
}
}
}
finally {
lock.lock();
try {
operationMap.remove(operation);
stack.removeFirst();
if (stack.isEmpty()) {
closingOperations.remove(tid);
}
} finally {
lock.unlock();
}
}
}
/* (non-Javadoc)
* @see org.glassfish.hk2.api.Context#shutdown()
*/
@Override
public void shutdown() {
Set<OperationHandleImpl<T>> toShutDown;
lock.lock();
try {
shuttingDown = true;
toShutDown = operationMap.keySet();
} finally {
lock.unlock();
}
try {
for (OperationHandleImpl<T> shutDown : toShutDown) {
shutDown.closeOperation();
}
}
finally {
lock.lock();
try {
operationMap.clear();
} finally {
lock.unlock();
}
}
}
/* (non-Javadoc)
* @see org.glassfish.hk2.api.Context#supportsNullCreation()
*/
@Override
public boolean supportsNullCreation() {
return false;
}
/* (non-Javadoc)
* @see org.glassfish.hk2.api.Context#isActive()
*/
@Override
public boolean isActive() {
return true;
}
public void setOperationManager(SingleOperationManager<T> manager) {
lock.lock();
try {
this.manager = manager;
} finally {
lock.unlock();
}
}
@Override
public String toString() {
return "OperationContext(" + getScope().getName() + "," + System.identityHashCode(this) + ")";
}
}