When we write code generally we end up writing synchronized code most of the time.
But in many situations, it makes sense not to block the execution and execute the code asynchronously.
In this article, we will consider one use case where writing asynchronous code makes sense.
Use Case
Consider a user apply for a product such as a credit card or debit card from front-end UI.
Now once at the backend, we receive user requests, we perform n number of use cases such as validation, transformation, persist to DB and sending acknowledgment email, etc.
Now all of these processes don’t have to be synchronous. For example, we can send emails to customers irrespective of saving them to the database.
So we can execute this piece of logic asynchronously.
Product Type
Product type is enum that represents the types of product a company offers.
Let’s create a user POJO that we will receive from client.
package AsyncExcercise;
public class User {
private int userId;
private String name;
private Enum productType;
private String timeStamp;
private String emailId;
public User(int userId, String name, Enum productType, String timeStamp, String emailId) {
this.userId = userId;
this.name = name;
this.productType = productType;
this.timeStamp = timeStamp;
this.emailId = emailId;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
public String getTimeStamp() {
return timeStamp;
}
public void setTimeStamp(String timeStamp) {
this.timeStamp = timeStamp;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Enum getProductType() {
return productType;
}
public void setProductType(Enum productType) {
this.productType = productType;
}
@Override
public String toString() {
return "User{" +
"userId=" + userId +
", name='" + name + '\'' +
", productType=" + productType +
", timeStamp='" + timeStamp + '\'' +
'}';
}
}
Apply Logic
Now once the client sends us the user object, we perform various operations on it.
First thing we do is check if a user is valid, if it is then we proceed to execute the sendMail logic asynchronously and then saves user to database.
// submit userRequest
private static void apply(User user){
if(validate()){
// send thank you mail to the customer
sendMail(user); // non blocking operation
// save to database
savetoDB(user); //
}
}
Send Email
Now, send email is implemented with CompletableFuture that takes supplier as an argument, we ran exceptionally to handle cases where we face some exceptions in send call.
If send call is successful then it prints success message otherwise exception is printed.
We are adding sleep time to see log of saveDB printed before sendMail to understand async behavior
In client code we are creating two user , one has email address and other just has empty email.
public static void main(String[] args) throws InterruptedException {
User user = new User(1,
"sam",
ProductType.CREDIT_CARD,
new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Date()),
"abc@gmail.com");
User user1 = new User(1,
"sam",
ProductType.CREDIT_CARD,
new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Date()),
"");
apply(user);
apply(user1);
Thread.sleep(3000);
}
Console Log
As we can see email log is printed later than the db log, which means email logic is executed asynchronously.
Conclusion
In this article, we wrote asynchronous code that executes without blocking our execution and saves on performance.
Java provides a Completable class to implement asynchronous behavior
Bonus Tip
If you want to upskill your Java, you should definitely check out this bestseller course
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept”, you consent to the use of ALL the cookies.
This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.
Cookie
Duration
Description
cookielawinfo-checkbox-analytics
11 months
This cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional
11 months
The cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary
11 months
This cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others
11 months
This cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance
11 months
This cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy
11 months
The cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.