Concurrency Safety Issues Caused by AOP Object Escape and Incorrect Advice Order in Spring
This article explains how improper use of AOP in Spring can cause object escape leading to concurrency safety problems, discusses issues such as asynchronous thread modifications, caching, and incorrect advice ordering with @Transaction, @Retryable, and dynamic datasource switching, and provides practical guidance to avoid these pitfalls.
In Java concurrency practice, especially when using Spring, AOP can unintentionally expose objects (object escape), creating concurrency safety hazards. When an object is passed as a method argument or returned value and later accessed by asynchronous threads or cached, concurrent modifications may occur, breaking thread safety.
Enabling asynchronous execution means the main thread and worker threads may both modify the same object, leading to race conditions. Similarly, caching an object makes it accessible to multiple threads; any modification by one thread can corrupt the shared state.
Beyond object escape, the order of AOP advices is critical. Incorrect ordering can cause business anomalies, such as when a distributed‑lock annotation and @Transaction are applied together. If the lock’s advice runs inside the transaction, the lock may be released before the transaction completes, causing data inconsistency. Therefore, the distributed‑lock AOP must execute before the transaction AOP.
Another example involves @Retryable and @Transaction on the same method. If the transaction interceptor runs before the retry interceptor, InnoDB’s repeatable‑read snapshot (ReadView) is created before the retry, making retries ineffective. Consequently, @Retryable must execute prior to @Transaction.
Dynamic datasource switching also suffers from ordering issues. When a routing datasource AOP and @Transaction coexist, the datasource must be switched before the transaction starts; otherwise, the transaction may operate on the wrong datasource, leading to failures. This ties back to ThreadLocal‑based context propagation.
In summary, while AOP is a powerful tool in Spring applications, developers should be aware of the following pitfalls:
Object escape of method arguments and return values, especially when asynchronous threads or caching are involved.
Incorrect advice ordering causing business errors, such as distributed‑lock vs. transaction, @Retryable vs. @Transaction, and dynamic datasource vs. transaction.
Understanding these issues and ensuring the correct execution order of AOP advices can help maintain concurrency safety and application correctness.
Cognitive Technology Team
Cognitive Technology Team regularly delivers the latest IT news, original content, programming tutorials and experience sharing, with daily perks awaiting you.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.