Following last article, I talk about the Async in Spring Framework. Basically, when we wanted to use the Async, we used Thread such as Callable and Future or Callback which was mentioned by last article. But, function which is @Async (annotaion in java) has been provided in Spring.
Look at the code 1 below
- code 1
This is the example for the Async in Spring. Before we talk about Async, I explain about ApplicationRunner(line:28). This is the Bean for executing something without containers such as Tomcat and Jetty etc at first. When you execute this code, Spring runs a code which is in ApplicationRunner and will be finished. In other words, it is a component for executing something what you want to do without containers. And in order to use the Async, @Async was used(line:9-20).(@EnableAsync is essential to use Async in line:5). When method which had @Async was called, they executed with new Thread.
This component doesn’t return the result because they have a type of the return which is void. But, sometimes, we need to return specific types which are String, Boolean etc. For getting a result data from Async, we have two ways. One is to use Future and the other is to use Callback. At first, I am going to talk Future.
Look at the code 2 below
- Add this method in TestService class
- Code 2
- Update ApplicationRunner code.
- Code 3
When you use primitive types as a return type for Async on the method, Spring can’t run this method as Async. You should use Future type and return **AsyncResult **. (line:2 and line10 in Code 2).
And you update the code like code 3 for getting a result data.
Until now, we have watched how to use Async in Spring. Acutally, In the web, we already have been using the Async in socket pool such as Servlet in containers which are Tomcat, Jetty etc. So we don’t need to use Async without special situation for sure. So then, when do we use Async method like this? It is a batch which need a lot of time to run something. So, How to?
- Insert data which is made in Async method in database.
- Keep the result Future data in web session.
- …
And I mentioned there were two ways in order to get result data in Async. One was @Async. What is the other one?
I will talk it next posting.
p.s. When you use async, you never use @Async without customizing. Then, how to customize the @Async?