DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • How Spring and Hibernate Simplify Web and Database Management
  • Functional Endpoints: Alternative to Controllers in WebFlux
  • Graceful Shutdown: Spring Framework vs Golang Web Services
  • Actuator Enhancements: Spring Framework 6.2 and Spring Boot 3.4

Trending

  • Kubeflow: Driving Scalable and Intelligent Machine Learning Systems
  • Performing and Managing Incremental Backups Using pg_basebackup in PostgreSQL 17
  • Revolutionizing Financial Monitoring: Building a Team Dashboard With OpenObserve
  • Docker Model Runner: Streamlining AI Deployment for Developers
  1. DZone
  2. Coding
  3. Frameworks
  4. Spring @Async and transaction management

Spring @Async and transaction management

By 
Jethro Borsje user avatar
Jethro Borsje
·
Jan. 16, 14 · Interview
Likes (5)
Comment
Save
Tweet
Share
127.3K Views

Join the DZone community and get the full member experience.

Join For Free

Introduction

There are cases in which it is necessary to execute pieces of code asynchronous. An example is the sending of a (JMS) message from your system to another system. If it is not important for the database transaction whether or not the message has been sent successfully you can send the message asynchronous. The advantage is that the user does not have to wait in the front-end while the message is being send. Another example of possible asynchronous execution is the case where messages have a clear ordering. In order to try to prevent message A from being overtaken by message B you might want to schedule the sending of message B asynchronous with a delay.

Spring Framework

Spring supports the asynchronous execution of methods on your @Components by means of the @Async annotation. When using this annotation on a method of your @Component Spring will always execute this method asynchronous. The Spring framework will use AOP (Aspect Oriented Programming) on the Spring proxy of the @Component to wrap calls to this method in a Runnable and schedule this Runnable on a task executor. This task executor has a thread pool and when a thread in the pool becomes available the Runnable will be executed on this thread. The caller of the method annotated with @Async does not wait untill the Runnable has been executed but terminates after the Runnable has been scheduled.

Return values

If the method to be executed asynchronously has a return value it should return a Future in its signature. This Future can be used by the caller to track the progress of the asynchronous task and to retrieve the result of the task once it has been completely executed. The @Async method should return an ASyncResult (which implements the Future interface) containing the actual result.

Transaction management

If the @Async annotation is being used extra care should be taken with respect to transactions. In normal circumstances (without @Async) a transaction gets propagated through the call hierarchy from one Spring @Component to the other.

However, when a @Transactional Spring @Component calls a method annotated with @Async this does not happen. The call to the asynchronous method is being scheduled and executed at a later time by a task executor and is thus handled as a 'fresh' call, i.e. without a transactional context. If the @Async method (or the @Component in which it is declared) is not @Transactional by itself Spring will not manage any needed transactions.

In case the method sends a message to an ESB (Enterprise Service Bus) using JMS (or another protocol) this can lead to problems, because you probably want to use the transaction manager declared in your Spring application context (typically a JTA transaction manager). In order to make Spring manage the transaction of the @Async method either the @Component or the method itself should declare the @Transactional annotation, this way Spring will manage the transaction even if a method is being executed asynchronous.

Caveats

A final reminder: both @Transactional and @Async work with AOP an proxying. The methods to which these annotation are applied should be public, otherwise the annotations are not picked up by Spring. When JUnit testing methods annotated with @Async in combination with transactions and automatic rollbacks extra care should be taken, this will be the topic of another blog post in the near future.

Spring Framework

Opinions expressed by DZone contributors are their own.

Related

  • How Spring and Hibernate Simplify Web and Database Management
  • Functional Endpoints: Alternative to Controllers in WebFlux
  • Graceful Shutdown: Spring Framework vs Golang Web Services
  • Actuator Enhancements: Spring Framework 6.2 and Spring Boot 3.4

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!