0
# Transaction Synchronization
1
2
Spring's transaction synchronization provides utilities for coordinating resources and callbacks within transaction boundaries.
3
4
## TransactionSynchronizationManager
5
6
```java { .api }
7
public abstract class TransactionSynchronizationManager {
8
public static boolean isSynchronizationActive();
9
public static void initSynchronization();
10
public static void registerSynchronization(TransactionSynchronization synchronization);
11
public static List<TransactionSynchronization> getSynchronizations();
12
public static void clearSynchronization();
13
14
public static boolean isCurrentTransactionReadOnly();
15
public static void setCurrentTransactionReadOnly(boolean readOnly);
16
public static String getCurrentTransactionName();
17
public static void setCurrentTransactionName(String name);
18
19
public static boolean isActualTransactionActive();
20
public static void setActualTransactionActive(boolean active);
21
}
22
```
23
24
## TransactionSynchronization Interface
25
26
```java { .api }
27
public interface TransactionSynchronization {
28
int STATUS_COMMITTED = 0;
29
int STATUS_ROLLED_BACK = 1;
30
int STATUS_UNKNOWN = 2;
31
32
default void suspend() {}
33
default void resume() {}
34
default void flush() {}
35
default void beforeCommit(boolean readOnly) {}
36
default void beforeCompletion() {}
37
default void afterCommit() {}
38
default void afterCompletion(int status) {}
39
}
40
```
41
42
## Usage Examples
43
44
```java
45
@Service
46
public class SynchronizedService {
47
48
public void performWithSynchronization() {
49
TransactionSynchronizationManager.registerSynchronization(
50
new TransactionSynchronization() {
51
@Override
52
public void afterCommit() {
53
// Cleanup after successful commit
54
cleanupResources();
55
}
56
57
@Override
58
public void afterCompletion(int status) {
59
if (status == STATUS_ROLLED_BACK) {
60
// Handle rollback
61
handleRollback();
62
}
63
}
64
});
65
}
66
}
67
```