| 1 | # Transaction Synchronization |
| 2 | |
| 3 | ## Decision |
| 4 | |
| 5 | The EDC `TransactionContext` will add the ability to register transaction synchronizations to receive callbacks prior to when a transaction is committed or rolled back. |
| 6 | |
| 7 | ## Rationale |
| 8 | |
| 9 | Transaction synchronization is a well-established pattern (.cf JTA) and will be used to automatically close resources and reduce the risk of runtime resource leaks. For example, |
| 10 | `SqlQueryExecutor` will use a transaction synchronization to close JDBC resources associated with streams returned from the `executeQuery` method: |
| 11 | |
| 12 | ` |
| 13 | public static <T> Stream<T> executeQuery(Connection connection, boolean closeConnection, ResultSetMapper<T> resultSetMapper, String sql, Object... arguments) |
| 14 | ` |
| 15 | |
| 16 | ## Approach |
| 17 | |
| 18 | Synchronizations must implement the `TransactionSynchronization` interface: |
| 19 | |
| 20 | ` |
| 21 | @FunctionalInterface |
| 22 | interface TransactionSynchronization { |
| 23 | void beforeCompletion(); |
| 24 | } |
| 25 | ` |
| 26 | Transaction synchronizations are registered using the `registerSynchronization` method on `TransactionContext` and will be associated with the active transaction context associated |
| 27 | with the current thread: |
| 28 | |
| 29 | ` |
| 30 | void registerSynchronization(TransactionSynchronization sync); |
| 31 | ` |
| 32 | |
| 33 | Transaction synchronizations must only be registered when a transaction is active and will be cleared after the transaction commits or is rolled back. Transaction synchronizations |
| 34 | will be supported across all `TransactionContext` implementations. |