Effective Advice on Spring @Async (ExceptionHandler): Part 2

In this article, I am going to discuss, how to catch Exception while you are using @Async annotation with Spring boot. Before deep diving to Exception handler I hope everyone who is reading this article, read my first part, If not I encourage you to do so, here is the link.

While you are forking thread from the main thread possibly you have two options.

1. Fire and forget :: you just fork a thread , assign some work to that thread, and just forget, at this moment,  you do not bother with the outcome as you do not need this information in order to execute next business logic, generally it's return type is void, let's understand with an example, Say you are in a process of  sending salary to the employees,  as a part of that you send an email to each employee attaching respective salary slip, and you do it asynchronously. Obviously sending salary slip via email to the employee is not a part of your core business logic, it is a cross-cutting concern, it is a good to have a feature(Some cases it is must have, then you adopt retrying, or schedule mechanism) rather than must to have.

2. Fire with Callback:: Here you fork a thread from the main thread and assign some work to that thread then attach a Callback. After that, the main thread proceeds with other tasks but the main thread keeps checking the callback for the result. The main thread needs that outcome from sub-thread as a form of callback to execute further.

Say you are preparing an Employee report,  Your software stores employee information in different backends based on the data category. , say General Service hold Employees general data (name, birthday, sex, address) and financial service holds(Salary, Tax, PF related data), so you fork two threads parallelly one for general service one for financial service, but you need both data to proceed further as in the report you need to combine both the data. So in the main thread, you want those results as a callback from subthreads, generally, we do it by CompletebleFuture(read Callable with Future).

In the above scenarios, if all is well that is the ideal case, but in the real-time exception can happen, then how you will handle Exception in the above two scenarios?

In the second scenario, It is very easy as result comes as a callback, whatever the result it is(Success or Failure), in case of failure,  Exception wrapped inside CompltebleFuture you can check the same and handle it in the main thread. Not a big deal,  basic java code. So I will skip that.

But Scenario one is tricky, you fork a thread with some business case,  how you can be sure that is a success, or if that is failure how you will debug it, how you will get a trace that something goes wrong?

The solution is very simple, You need to inject your own Exception handler so that if an exception occurs while you are executing an Async method it should pass the control to that handler and then handles what to do with that,  very Simple isn't it.

To achieve that we need to follow below steps.

1. AsyncConfigurer::  AsyncConfigurere is an Interface provided by Spring, It provides two methods one is if you want to override the TaskExecutor(Threadpool) another is an Exception handler where you can inject your exception handler so it can catch the uncaught exceptions. You can create your own class and implements that one directly. but I will not do that, as an alternative, I will use Spring  AsyncConfigurerSupport class which annotates by @Configuration and @EnableAsync, and provides a default implementation.


package com.example.ask2shamik.springAsync;

import java.lang.reflect.Method;
import java.util.concurrent.Executor;

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
import org.springframework.lang.Nullable;
import org.springframework.scheduling.annotation.AsyncConfigurerSupport;
import org.springframework.scheduling.annotation.EnableAsync;



@Configuration
@EnableAsync
public class CustomConfiguration extends AsyncConfigurerSupport {
@Override
public Executor getAsyncExecutor() {
return new SimpleAsyncTaskExecutor();
}


@Override
@Nullable
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {

return (throwable, method, obj)->{
System.out.println("Exception Caught in Thread - " + Thread.currentThread().getName());
System.out.println("Exception message - " + throwable.getMessage());
System.out.println("Method name - " + method.getName());
for (Object param : obj) {
System.out.println("Parameter value - " + param);
}
};
}

}

Please note that, In case of, getAsyncExecutor method, I am not going to create any new Executor as I do not want to use my own task executor so I use Spring default SimpleAsyncExecutor.

But  I need my custom uncaught exception handler to handle any uncaught Exception so I create a lambda expression which actually extends  AsyncUncaughtExceptionHandler class and overrides handleuncaughtexception method.

In this way, I instruct Spring while loading, use my application specific AsyncConfugurer(CustomConfiguration)  and use my lambda expression as an Exception handler.



Now I create an async method which will throw an Exception.

package com.example.ask2shamik.springAsync.demo;

import java.util.Map;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
@Component
public class AsyncMailTrigger {

@Async
public void senMailwithException() throws Exception{
throw new Exception("SMTP Server not found :: orginated from Thread :: " + Thread.currentThread().getName());

}

}

Now, Create a caller method.
package com.example.ask2shamik.springAsync.demo;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
@Component
public class AsyncCaller {

@Autowired
AsyncMailTrigger asyncMailTriggerObject;

public void rightWayToCall() throws Exception {
System.out.println("Calling From rightWayToCall Thread " + Thread.currentThread().getName());
asyncMailTriggerObject.senMailwithException();

}

}

Now let's run this Application using Spring boot, to see How it catch the Exception thrown by the method sendMailwithException.

package com.example.ask2shamik.springAsync;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableAsync;

import com.example.ask2shamik.springAsync.demo.AsyncCaller;

@SpringBootApplication
public class DemoApplication {

@Autowired
AsyncCaller caller;

public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);

}
 @Bean
 public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
        return args -> {
        caller.rightWayToCall();
         };
    }


}

And the output is

Calling From rightWayToCall Thread main
Exception Caught in Thread - SimpleAsyncTaskExecutor-1
Exception message - SMTP Server not found:: originated from Thread:: SimpleAsyncTaskExecutor-1
Method name - senMailwithException

Conclusion: Hope you like the tutorial, If you have a question please put it in the comment box and stay tuned for part 3.

Effective Advice on Spring @Async-Part 1

As per the current trend, I can see from Juniors to Seniors all are using Spring boot as a weapon to build software. Why that should not be, it is developer friendly and its "convention over configuration" style helps the developer to only focus on business logic If they are ignorant how Springs works still just seeing a Spring boot tutorial one can start using Spring boot.
I like that one,  at least major taskforce in support project is now being utilized as they do not have to know Spring inner details, just put some annotations and write the business code and voila, with that said sometimes in some cases  you have to know "How it works", what I am trying to say, you need to know your tool better then only you can utilize your tool as a PRO.
In this Article, I will give you an idea of how you can use asynchronous processing in Spring.
Any pieces of logic, which is not directly associated with business logic (Cross-cutting concerns) or a logic whose response not needed in invoker context to determine next flow or any business computation is an ideal candidate of Asyncronization. Also Integrating two distributed system Asyncronization technique is being used to make them decoupled.
In Spring we can use Asynchronization using @Async annotation, but wait here if you use randomly @Async annotation on top of a method and think your method will be invoked as a asynchronous fashion in a separate thread you are wrong. you need to know How @Async works and it's limitations, without that you can't understand Async behavior.
How @Async Works?
When you put an @Async annotation on a method, underlying it creates a proxy of that object where @Async is defined (JDK Proxy/CGlib) based on the proxyTargetClass property. then Spring tries to find a thread pool associated with the context, to submit this method's logic as a separate path of execution to be exact it searches a unique TaskExecutor bean or a bean named as taskExecutor if not found then use default SimpleAsyncTaskExecutor.
Now, as it creates a proxy and submits the job to TaskExecutor thread pool, it has few limitations which you must have to know, otherwise, you will scratch your head why your Async is not worked or create a new thread!!!

Limitations of @Async 
1. Suppose you write a class and identify a method which will act as Async and put @Async on top of that method, now if you want to use that class from another class by creating local instance then it will not fire the async, It has to be picked up by Spring @ComponentScan annotation or created inside a class marked as @Configuration.

Async Annotation use in a Class
package com.example.ask2shamik.springAsync.demo;
import java.util.Map;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
@Component
public class AsyncMailTrigger {
@Async
public void senMail(Map<String,String> properties) {
System.out.println("Trigger mail in a New Thread :: "  + Thread.currentThread().getName());
properties.forEach((K,V)->System.out.println("Key::" + K + " Value ::" + V));
}
}

Caller Class
package com.example.ask2shamik.springAsync.demo;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class AsyncCaller {

@Autowired
AsyncMailTrigger asyncMailTriggerObject;

public void rightWayToCall() {
System.out.println("Calling From rightWayToCall Thread " + Thread.currentThread().getName());
asyncMailTriggerObject.senMail(populateMap());

}

public void wrongWayToCall() {
System.out.println("Calling From wrongWayToCall Thread " + Thread.currentThread().getName());
AsyncMailTrigger asyncMailTriggerObject = new AsyncMailTrigger();
asyncMailTriggerObject.senMail(populateMap());
}

private Map<String,String> populateMap(){
Map<String,String> mailMap= new HashMap<String,String>();
mailMap.put("body", "A Ask2Shamik Article");
return mailMap;

}
}

Here I create two methods one use the @Autowired version of AsyncMailtrigger, which will be picked by @ComponentScan but in a WrongWayTo Call method I create the object in local so it will not be picked up by @ComponentScan hence not spawn a new thread it executed inside the main thread.
Outcome
 Calling From rightWayToCall Thread main
2019-03-09 14:08:28.893  INFO 8468 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
Trigger mail in a New Thread :: task-1
Key::body Value ::A Ask2Shamik Article
++++++++++++++++
Calling From wrongWayToCall Thread main
Trigger mail in a New Thread :: main
Key::body Value ::A Ask2Shamik Article

2. Never use @Async on top of a private method as in runtime it will not able to create a proxy, so not working.
 @Async
private void senMail() {
System.out.println("A proxy on Private method "  + Thread.currentThread().getName());
} 
3. Never writes Async method in the same class where caller method invokes the same Async method , so always remember using this reference Async not worked, because in this case,although it creates a proxy but this call bypass the proxy and call directly the method so Thread will not be spawned and developer in a wrong assumption that, it will work like async fashion, Most developers implement async in this way carelessly, so be very careful while writing Async, Caller method  should be in different class, while calling  Async method.


Example
package com.example.ask2shamik.springAsync.demo;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
@Component
public class AsyncCaller {
@Autowired
AsyncMailTrigger asyncMailTriggerObject;

public void rightWayToCall() {
System.out.println("Calling From rightWayToCall Thread " + Thread.currentThread().getName());
asyncMailTriggerObject.senMail(populateMap());
}
public void wrongWayToCall() {
System.out.println("Calling From wrongWayToCall Thread " + Thread.currentThread().getName());
this.senMail(populateMap());
}
private Map<String,String> populateMap(){
Map<String,String> mailMap= new HashMap<String,String>();
mailMap.put("body", "A Ask2Shamik Article");
return mailMap;

}
@Async
public void senMail(Map<String,String> properties) {
System.out.println("Trigger mail in a New Thread :: "  + Thread.currentThread().getName());
properties.forEach((K,V)->System.out.println("Key::" + K + " Value ::" + V));
}
} 

 The last piece is to execute the application, please note we use @EnableAsync annotation, by this Spring submits @Async methods in a background thread pool. This class can customize,  the used Executor by defining a new bean, I will discuss it in later with an Example How to do that.
 package com.example.ask2shamik.springAsync;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableAsync;
import com.example.ask2shamik.springAsync.demo.AsyncCaller;

@SpringBootApplication
@EnableAsync
public class DemoApplication {

@Autowired
AsyncCaller caller;
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);

}
 @Bean
 public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
        return args -> {
        caller.rightWayToCall();
        Thread.sleep(1000);
        System.out.println("++++++++++++++++");
        Thread.sleep(1000);
        caller.wrongWayToCall();

        };
    }
}

Conclusion: Hope now you are able to understand How Async works internally and its limitation, now in next Article I will discuss on Exception handler in Async.

#Ask2Shamik Presents Microservice communication using Feign Template Spring boot
In this Video, we will learn What do you mean by Feign client?
Step by Step implementation of Sync communication via Feign client using Spring Cloud


Ask2Shamik Presents a simple way to understand Microservice communication by Live coding

#Ask2Shamik Presents Microservice communication via Rest Template using Spring boot
In this Video, we will learn What do you mean by Microservice Communication?
Step by Step implementation of Sync communication via Resttemplate using Spring Cloud
How to Communicate with the config server to the resolute property using Spring-boot?

Ask2SHamik Presents Eureka server Live coding with Step by Step explanation

Ask2SHamik Presents Eureka server Live coding with Step by Step explanation, to grasp Microservice concepts come and subscribe right now.
#Ask2shamik #javaonfly #shamik #microservice #springboot #java #Dzone #JCG
Ask2Shamik presents Key points you want to know about Service discovery(Eureka server).
Take away from this video::
What is service discovery pattern?
Why is it needed in Microservice?
Demerits of the Traditional Load Balancer.
What is Eureka server?
How Multiple Eureka server communicate with each other.
Microservices comminucation.

Ask2Shamik Presents a brand new video on Microservice Pivot components(English Version).

Microservice is Hot Cake now To cook Microservice best way, you want to know what ingredients are most important? So you get an optimum experience, Check this video Which Touch bases on Each important components like Zuul, Eureka, Consul, Zookeeper, Ribbon, Zipkin, Hytrix, Splunk, ELK

Have a dilemma What to choose for your new project Monolith or Microservice? Check this Video on Ask2Shamik.

Have a dilemma What to choose for your new project Monolith or Microservice? Ask2Shamik presents 5 Checklists to choose wisely Monolith or Microservice.

Ask2Shamik Presents, A talk on Microservice Characteristics.

Ask2Shamik Presents, A talk on Microservice Characteristics, where you can learn what are the common misconceptions on Microservices.
Microservices Characteristics and deep dive to each character.
Subscribe to Ask2shamik to get more latest videos on Microservices.
#ask2shamik #javaonfly #shamik #Microservices #Springboot #dzone #jcg

Ask2Shamik Presents Why Microservice?


Ask2Shamik Presents a video called Why Microservices,

 Take away from this videos

1. Why Microservices needed?
2. What are the pain points of Monolith Architecture?

3. What are the benefits of Microservices? Please see and subscribe on Ask2Shamik, it is a brand new Youtube channel from Javaonfly production.

Hope you enjoy it!!!

Building Layered Architecture just in 3 minutes: Final Part

I am sure that you have enjoyed the part1 where just a blink of an eye we set up an in-memory database, create a Repository class using Spring Data JPA and insert data using initDataloader by Spring boot.
In this tutorial, we will expose those employee data to UI, The Classic  MVC pattern using Spring boot.
The Service Part:: In my previous article I have created an EmployeeRepository interface & Spring boot provide its implementation at runtime, now I want this data to be guided to the Service Layer. To achieve that, I need to inject that Repository to Service layer, and define the CRUD methods which are doing nothing but calls the Repositories CRUD methods, Now you may be wondering, the EmployeeRepository interface  is empty and it extends CRUDRepository, where you can only find the declaration of CRUD methods, Now the question is, where are the Implementations ?

Again the Answer is Spring-boot on the runtime it creates an Implementation class which has all the CRUD methods implementations. Interesting isn't it,  We just declare an interface and Container creates  all the stuff for us, and we save lots of our precious time, get rid of silly mistakes etc. really an IOC(Inversion of Control)
Let's see How the Service part looks like, Please note for simplicity, I print the messages in the console using Sysout, But in the real project don't ever do this, use Logger always.

package com.example.layerdArchitechture.service;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.layerdArchitechture.entity.Employee;
import com.example.layerdArchitechture.repository.EmployeeRepositiry;

@Service
public class EmployeeService {
@Autowired
EmployeeRepositiry repo;
public Employee addEmployee(Employee emp) {
emp = repo.save(emp);
System.out.println("Employee saved::" + emp);
return emp;
}
public Optional<Employee> findEmployeeById(Long empId) {
Optional<Employee> emp = repo.findById(empId);
System.out.println("Employee found::" + emp);
return emp;
}
public Iterable<Employee> findAllEmployee() {
return repo.findAll();
}
public void deleteEmployeeById(Employee emp) {
repo.delete(emp);
System.out.println("Employee deleted::" + emp);
}
}

Yeah, Our service Layer is ready, Now I need a Controller part which will act as a delegator, takes data from UI send it to Service and Vice versa, I personally recommend to use Controller as a thin layer which just porting data from UI to service and service to UI and maybe doing some data format conversion stuffs nothing more than that.
Before showing you the code of the controller let me remind you I have not use a proper Spring controller which forward the response to a view rather, I use a RestController which directly deliver the response payload in JSON / XML format, based on the Produces property. by default it is JSON.
In Controller, we map the URL pattern to a controller method bind any data coming from a form into a  Model the "M " part of MVC.
Let's see the code.
package com.example.layerdArchitechture.controller;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.layerdArchitechture.entity.Employee;
import com.example.layerdArchitechture.service.EmployeeService;
@RestController
public class EmployeeController {
@Autowired
EmployeeService service;
@RequestMapping("/TCS/employees")
public Iterable<Employee> findAllEmployee() {
return service.findAllEmployee();
}
@RequestMapping("/TCS/employee/{id}")
public Employee findbyId(@PathVariable Long id) {
Optional<Employee> emplyoeeContainer = service.findEmployeeById(id);
return emplyoeeContainer.isPresent()?emplyoeeContainer.get():null;
}
@RequestMapping("/TCS/employee/addDemoEmployee")
public Employee addEmployee() {
Employee emp = new Employee();
emp.setName("Demo Demo");
emp.setSex("M");
emp.setAddress("Demo");
return service.addEmployee(emp);
}

@RequestMapping("/TCS/employee/delete/{id}")
public String delete(@PathVariable Long id) {
Optional<Employee> emp = service.findEmployeeById(id);
if(emp.isPresent()) {
 service.deleteEmployeeById(emp.get());
 return "deleted Successfully";
}
return "Employee Not Exists, Not able to delete";
}
}

If you look at the Controller class, You can see I autowired the Service class then wrote CRUD methods(also map them with Url pattern) as a wrapper which internally calls Service Wrapper method which calls the Spring boot's Repository Implementation class.
Now If I run the spring boot application class and hit following URL in the browser
http://localhost:8080/TCS/employees
I can see the following response in Browser in JSON format.
[
  {
    "id": 1,
    "name": "Shamik Mitra",
    "address": "BagBazar",
    "sex": "M"
  },
  {
    "id": 2,
    "name": "Samir Mitra",
    "address": "BagBazar",
    "sex": "M"
  },
  {
    "id": 3,
    "name": "Swastika Basu",
    "address": "Baranagar",
    "sex": "F"
  }
]
Hope you enjoyed the post.