-
Notifications
You must be signed in to change notification settings - Fork 197
/
TransactionSynchronizationManager.java
504 lines (463 loc) · 21.9 KB
/
TransactionSynchronizationManager.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
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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
/*
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.micronaut.transaction.support;
import edu.umd.cs.findbugs.annotations.Nullable;
import io.micronaut.core.order.OrderUtil;
import io.micronaut.transaction.TransactionDefinition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
/**
* Central delegate that manages resources and transaction synchronizations per thread.
* To be used by resource management code but not by typical application code.
*
* <p>Supports one resource per key without overwriting, that is, a resource needs
* to be removed before a new one can be set for the same key.
* Supports a list of transaction synchronizations if synchronization is active.
*
* <p>Resource management code should check for thread-bound resources, e.g. JDBC
* Connections or Hibernate Sessions, via {@code getResource}. Such code is
* normally not supposed to bind resources to threads, as this is the responsibility
* of transaction managers. A further option is to lazily bind on first use if
* transaction synchronization is active, for performing transactions that span
* an arbitrary number of resources.
*
* <p>Transaction synchronization must be activated and deactivated by a transaction
* manager via {@link #initSynchronization()} and {@link #clearSynchronization()}.
* This is automatically supported by {@link AbstractSynchronousTransactionManager},
* and thus by all standard transaction managers.
*
* <p>Resource management code should only register synchronizations when this
* manager is active, which can be checked via {@link #isSynchronizationActive};
* it should perform immediate resource cleanup else. If transaction synchronization
* isn't active, there is either no current transaction, or the transaction manager
* doesn't support transaction synchronization.
*
* <p>Synchronization is for example used to always return the same resources
* within a JTA transaction, e.g. a JDBC Connection or a Hibernate Session for
* any given DataSource or SessionFactory, respectively.
*
* @author Juergen Hoeller
* @since 02.06.2003
* @see #isSynchronizationActive
* @see #registerSynchronization
* @see TransactionSynchronization
* @see AbstractSynchronousTransactionManager#setTransactionSynchronization
*/
public abstract class TransactionSynchronizationManager {
private static final Logger LOG = LoggerFactory.getLogger(TransactionSynchronizationManager.class);
@SuppressWarnings("unchecked")
private static final ThreadLocal<Map<Object, Object>> RESOURCES =
new ThreadLocal() {
@Override
public String toString() {
return "Transactional resources";
}
};
@SuppressWarnings("unchecked")
private static final ThreadLocal<Set<TransactionSynchronization>> SYNCHRONIZATIONS =
new ThreadLocal() {
@Override
public String toString() {
return "Transaction synchronizations";
}
};
@SuppressWarnings("unchecked")
private static final ThreadLocal<String> CURRENT_TRANSACTION_NAME =
new ThreadLocal() {
@Override
public String toString() {
return "Current transaction name";
}
};
@SuppressWarnings("unchecked")
private static final ThreadLocal<Boolean> CURRENT_TRANSACTION_READ_ONLY =
new ThreadLocal() {
@Override
public String toString() {
return "Current transaction read-only status";
}
};
@SuppressWarnings("unchecked")
private static final ThreadLocal<TransactionDefinition.Isolation> CURRENT_TRANSACTION_ISOLATION_LEVEL =
new ThreadLocal() {
@Override
public String toString() {
return "Current transaction isolation level";
}
};
@SuppressWarnings("unchecked")
private static final ThreadLocal<Boolean> ACTUAL_TRANSACTION_ACTIVE =
new ThreadLocal() {
@Override
public String toString() {
return "Actual transaction active";
}
};
//-------------------------------------------------------------------------
// Management of transaction-associated resource handles
//-------------------------------------------------------------------------
/**
* Return all resources that are bound to the current thread.
* <p>Mainly for debugging purposes. Resource managers should always invoke
* {@code hasResource} for a specific resource key that they are interested in.
* @return a Map with resource keys (usually the resource factory) and resource
* values (usually the active resource object), or an empty Map if there are
* currently no resources bound
* @see #hasResource
*/
public static Map<Object, Object> getResourceMap() {
Map<Object, Object> map = RESOURCES.get();
return (map != null ? Collections.unmodifiableMap(map) : Collections.emptyMap());
}
/**
* Check if there is a resource for the given key bound to the current thread.
* @param key the key to check (usually the resource factory)
* @return if there is a value bound to the current thread
* @see ResourceTransactionManager#getResourceFactory()
*/
public static boolean hasResource(Object key) {
Object actualKey = TransactionSynchronizationUtils.unwrapResourceIfNecessary(key);
Object value = doGetResource(actualKey);
return (value != null);
}
/**
* Retrieve a resource for the given key that is bound to the current thread.
* @param key the key to check (usually the resource factory)
* @return a value bound to the current thread (usually the active
* resource object), or {@code null} if none
* @see ResourceTransactionManager#getResourceFactory()
*/
@Nullable
public static Object getResource(Object key) {
Object actualKey = TransactionSynchronizationUtils.unwrapResourceIfNecessary(key);
Object value = doGetResource(actualKey);
if (value != null && LOG.isTraceEnabled()) {
LOG.trace("Retrieved value [" + value + "] for key [" + actualKey + "] bound to thread [" +
Thread.currentThread().getName() + "]");
}
return value;
}
/**
* Actually check the value of the resource that is bound for the given key.
*/
@Nullable
private static Object doGetResource(Object actualKey) {
Map<Object, Object> map = RESOURCES.get();
if (map == null) {
return null;
}
Object value = map.get(actualKey);
// Transparently remove ResourceHolder that was marked as void...
if (value instanceof ResourceHolder && ((ResourceHolder) value).isVoid()) {
map.remove(actualKey);
// Remove entire ThreadLocal if empty...
if (map.isEmpty()) {
RESOURCES.remove();
}
value = null;
}
return value;
}
/**
* Bind the given resource for the given key to the current thread.
* @param key the key to bind the value to (usually the resource factory)
* @param value the value to bind (usually the active resource object)
* @throws IllegalStateException if there is already a value bound to the thread
* @see ResourceTransactionManager#getResourceFactory()
*/
public static void bindResource(Object key, Object value) throws IllegalStateException {
Object actualKey = TransactionSynchronizationUtils.unwrapResourceIfNecessary(key);
Objects.requireNonNull(value, "Value must not be null");
Map<Object, Object> map = RESOURCES.get();
// set ThreadLocal Map if none found
if (map == null) {
map = new HashMap<>();
RESOURCES.set(map);
}
Object oldValue = map.put(actualKey, value);
// Transparently suppress a ResourceHolder that was marked as void...
if (oldValue instanceof ResourceHolder && ((ResourceHolder) oldValue).isVoid()) {
oldValue = null;
}
if (oldValue != null) {
throw new IllegalStateException("Already value [" + oldValue + "] for key [" +
actualKey + "] bound to thread [" + Thread.currentThread().getName() + "]");
}
if (LOG.isTraceEnabled()) {
LOG.trace("Bound value [" + value + "] for key [" + actualKey + "] to thread [" +
Thread.currentThread().getName() + "]");
}
}
/**
* Unbind a resource for the given key from the current thread.
* @param key the key to unbind (usually the resource factory)
* @return the previously bound value (usually the active resource object)
* @throws IllegalStateException if there is no value bound to the thread
* @see ResourceTransactionManager#getResourceFactory()
*/
public static Object unbindResource(Object key) throws IllegalStateException {
Object actualKey = TransactionSynchronizationUtils.unwrapResourceIfNecessary(key);
Object value = doUnbindResource(actualKey);
if (value == null) {
throw new IllegalStateException(
"No value for key [" + actualKey + "] bound to thread [" + Thread.currentThread().getName() + "]");
}
return value;
}
/**
* Unbind a resource for the given key from the current thread.
* @param key the key to unbind (usually the resource factory)
* @return the previously bound value, or {@code null} if none bound
*/
@Nullable
public static Object unbindResourceIfPossible(Object key) {
Object actualKey = TransactionSynchronizationUtils.unwrapResourceIfNecessary(key);
return doUnbindResource(actualKey);
}
/**
* Actually remove the value of the resource that is bound for the given key.
*/
@Nullable
private static Object doUnbindResource(Object actualKey) {
Map<Object, Object> map = RESOURCES.get();
if (map == null) {
return null;
}
Object value = map.remove(actualKey);
// Remove entire ThreadLocal if empty...
if (map.isEmpty()) {
RESOURCES.remove();
}
// Transparently suppress a ResourceHolder that was marked as void...
if (value instanceof ResourceHolder && ((ResourceHolder) value).isVoid()) {
value = null;
}
if (value != null && LOG.isTraceEnabled()) {
LOG.trace("Removed value [" + value + "] for key [" + actualKey + "] from thread [" +
Thread.currentThread().getName() + "]");
}
return value;
}
//-------------------------------------------------------------------------
// Management of transaction synchronizations
//-------------------------------------------------------------------------
/**
* Return if transaction synchronization is active for the current thread.
* Can be called before register to avoid unnecessary instance creation.
* @see #registerSynchronization
* @return True if a synchronization is active
*/
public static boolean isSynchronizationActive() {
return (SYNCHRONIZATIONS.get() != null);
}
/**
* Activate transaction synchronization for the current thread.
* Called by a transaction manager on transaction begin.
* @throws IllegalStateException if synchronization is already active
*/
public static void initSynchronization() throws IllegalStateException {
if (isSynchronizationActive()) {
throw new IllegalStateException("Cannot activate transaction synchronization - already active");
}
LOG.trace("Initializing transaction synchronization");
SYNCHRONIZATIONS.set(new LinkedHashSet<>());
}
/**
* Register a new transaction synchronization for the current thread.
* Typically called by resource management code.
* <p>Note that synchronizations can implement the
* {@link io.micronaut.core.order.Ordered} interface.
* They will be executed in an order according to their order value (if any).
* @param synchronization the synchronization object to register
* @throws IllegalStateException if transaction synchronization is not active
* @see io.micronaut.core.order.Ordered
*/
public static void registerSynchronization(TransactionSynchronization synchronization)
throws IllegalStateException {
Objects.requireNonNull(synchronization, "TransactionSynchronization must not be null");
Set<TransactionSynchronization> synchs = SYNCHRONIZATIONS.get();
if (synchs == null) {
throw new IllegalStateException("Transaction synchronization is not active");
}
synchs.add(synchronization);
}
/**
* Return an unmodifiable snapshot list of all registered synchronizations
* for the current thread.
* @return unmodifiable List of TransactionSynchronization instances
* @throws IllegalStateException if synchronization is not active
* @see TransactionSynchronization
*/
public static List<TransactionSynchronization> getSynchronizations() throws IllegalStateException {
Set<TransactionSynchronization> synchs = SYNCHRONIZATIONS.get();
if (synchs == null) {
throw new IllegalStateException("Transaction synchronization is not active");
}
// Return unmodifiable snapshot, to avoid ConcurrentModificationExceptions
// while iterating and invoking synchronization callbacks that in turn
// might register further synchronizations.
if (synchs.isEmpty()) {
return Collections.emptyList();
} else {
// Sort lazily here, not in registerSynchronization.
List<TransactionSynchronization> sortedSynchs = new ArrayList<>(synchs);
OrderUtil.sort(sortedSynchs);
return Collections.unmodifiableList(sortedSynchs);
}
}
/**
* Deactivate transaction synchronization for the current thread.
* Called by the transaction manager on transaction cleanup.
* @throws IllegalStateException if synchronization is not active
*/
public static void clearSynchronization() throws IllegalStateException {
if (!isSynchronizationActive()) {
throw new IllegalStateException("Cannot deactivate transaction synchronization - not active");
}
LOG.trace("Clearing transaction synchronization");
SYNCHRONIZATIONS.remove();
}
//-------------------------------------------------------------------------
// Exposure of transaction characteristics
//-------------------------------------------------------------------------
/**
* Expose the name of the current transaction, if any.
* Called by the transaction manager on transaction begin and on cleanup.
* @param name the name of the transaction, or {@code null} to reset it
* @see io.micronaut.transaction.TransactionDefinition#getName()
*/
public static void setCurrentTransactionName(@Nullable String name) {
CURRENT_TRANSACTION_NAME.set(name);
}
/**
* Return the name of the current transaction, or {@code null} if none set.
* To be called by resource management code for optimizations per use case,
* for example to optimize fetch strategies for specific named transactions.
* @see io.micronaut.transaction.TransactionDefinition#getName()
* @return The current transaction name
*/
@Nullable
public static String getCurrentTransactionName() {
return CURRENT_TRANSACTION_NAME.get();
}
/**
* Expose a read-only flag for the current transaction.
* Called by the transaction manager on transaction begin and on cleanup.
* @param readOnly {@code true} to mark the current transaction
* as read-only; {@code false} to reset such a read-only marker
* @see io.micronaut.transaction.TransactionDefinition#isReadOnly()
*/
public static void setCurrentTransactionReadOnly(boolean readOnly) {
CURRENT_TRANSACTION_READ_ONLY.set(readOnly ? Boolean.TRUE : null);
}
/**
* Return whether the current transaction is marked as read-only.
* To be called by resource management code when preparing a newly
* created resource (for example, a Hibernate Session).
* <p>Note that transaction synchronizations receive the read-only flag
* as argument for the {@code beforeCommit} callback, to be able
* to suppress change detection on commit. The present method is meant
* to be used for earlier read-only checks, for example to set the
* flush mode of a Hibernate Session to "FlushMode.NEVER" upfront.
* @see io.micronaut.transaction.TransactionDefinition#isReadOnly()
* @see TransactionSynchronization#beforeCommit(boolean)
* @return Whether the transaction is read only
*/
public static boolean isCurrentTransactionReadOnly() {
return (CURRENT_TRANSACTION_READ_ONLY.get() != null);
}
/**
* Expose an isolation level for the current transaction.
* Called by the transaction manager on transaction begin and on cleanup.
* @param isolationLevel the isolation level to expose, according to the
* JDBC Connection constants (equivalent to the corresponding
* TransactionDefinition constants), or {@code null} to reset it
* @see java.sql.Connection#TRANSACTION_READ_UNCOMMITTED
* @see java.sql.Connection#TRANSACTION_READ_COMMITTED
* @see java.sql.Connection#TRANSACTION_REPEATABLE_READ
* @see java.sql.Connection#TRANSACTION_SERIALIZABLE
* @see io.micronaut.transaction.TransactionDefinition.Isolation#READ_UNCOMMITTED
* @see io.micronaut.transaction.TransactionDefinition.Isolation#READ_COMMITTED
* @see io.micronaut.transaction.TransactionDefinition.Isolation#REPEATABLE_READ
* @see io.micronaut.transaction.TransactionDefinition.Isolation#SERIALIZABLE
* @see io.micronaut.transaction.TransactionDefinition#getIsolationLevel()
*/
public static void setCurrentTransactionIsolationLevel(@Nullable TransactionDefinition.Isolation isolationLevel) {
CURRENT_TRANSACTION_ISOLATION_LEVEL.set(isolationLevel);
}
/**
* Return the isolation level for the current transaction, if any.
* To be called by resource management code when preparing a newly
* created resource (for example, a JDBC Connection).
* @return the currently exposed isolation level, according to the
* JDBC Connection constants (equivalent to the corresponding
* TransactionDefinition constants), or {@code null} if none
* @see java.sql.Connection#TRANSACTION_READ_UNCOMMITTED
* @see java.sql.Connection#TRANSACTION_READ_COMMITTED
* @see java.sql.Connection#TRANSACTION_REPEATABLE_READ
* @see java.sql.Connection#TRANSACTION_SERIALIZABLE
* @see io.micronaut.transaction.TransactionDefinition.Isolation#READ_UNCOMMITTED
* @see io.micronaut.transaction.TransactionDefinition.Isolation#READ_COMMITTED
* @see io.micronaut.transaction.TransactionDefinition.Isolation#REPEATABLE_READ
* @see io.micronaut.transaction.TransactionDefinition.Isolation#SERIALIZABLE
* @see io.micronaut.transaction.TransactionDefinition#getIsolationLevel()
*/
@Nullable
public static TransactionDefinition.Isolation getCurrentTransactionIsolationLevel() {
return CURRENT_TRANSACTION_ISOLATION_LEVEL.get();
}
/**
* Expose whether there currently is an actual transaction active.
* Called by the transaction manager on transaction begin and on cleanup.
* @param active {@code true} to mark the current thread as being associated
* with an actual transaction; {@code false} to reset that marker
*/
public static void setActualTransactionActive(boolean active) {
ACTUAL_TRANSACTION_ACTIVE.set(active ? Boolean.TRUE : null);
}
/**
* Return whether there currently is an actual transaction active.
* This indicates whether the current thread is associated with an actual
* transaction rather than just with active transaction synchronization.
* <p>To be called by resource management code that wants to discriminate
* between active transaction synchronization (with or without backing
* resource transaction; also on PROPAGATION_SUPPORTS) and an actual
* transaction being active (with backing resource transaction;
* on PROPAGATION_REQUIRED, PROPAGATION_REQUIRES_NEW, etc).
* @see #isSynchronizationActive()
* @return Whether a transaction is active
*/
public static boolean isActualTransactionActive() {
return (ACTUAL_TRANSACTION_ACTIVE.get() != null);
}
/**
* Clear the entire transaction synchronization state for the current thread:
* registered synchronizations as well as the various transaction characteristics.
* @see #clearSynchronization()
* @see #setCurrentTransactionName
* @see #setCurrentTransactionReadOnly
* @see #setCurrentTransactionIsolationLevel
* @see #setActualTransactionActive
*/
public static void clear() {
SYNCHRONIZATIONS.remove();
CURRENT_TRANSACTION_NAME.remove();
CURRENT_TRANSACTION_READ_ONLY.remove();
CURRENT_TRANSACTION_ISOLATION_LEVEL.remove();
ACTUAL_TRANSACTION_ACTIVE.remove();
}
}