SlideShare a Scribd company logo
1 of 18
Asynchronous Programming
In Spring Framework
Presented By-:
Aayush Chimaniya
Contents-:
1. Introduction Of Asynchronous
2. Difference Between SYNC & MULTITHREADING & ASYNC
Programming.
3. Diagrammatic Differences
4. How Works Multithreading Programming & Asynchronous Programming
5. USE CASEs Of Asynchronous
6. Explore the asynchronous execution support in Spring Step-By-Step
7. Exception Handling In Asynchronous Programming
8. CONs Of Asynchronous Programming
9. Conclusion
INTRODUCTION OF ASYNCHRONOUS PROGRAMMING
1.Asynchronous programming is a form of parallel programming.
2. It allows a unit of work, to run separately from the primary thread. When the work
is complete, it notifies to the main thread.
3. It uses the same thread to process multiple requests without any request blocking the
thread.
4.Asynchronous programming has actually been around for a long time, but in recent
years, it’s become more widely used.
6.It helps to developers to
to run applications faster.
DIAGRAMMATIC DIFFERNECES
Seprate
Thread
DIFFERENCE BETWEEN SYNC & MULTITHREADING & ASYNC
PROGRAMMING
-Sync is single-thread, means one program will run at a time.
Sync is blocking pattern, means it can send one request to the server at a time
and will wait for, that request to be answered by the server.
-Multi-Thread is multi-thread programs, But every thread has assigned seprate task.
Multithreading programming is all about concurrent execution
of different functions.
-Async is multi-thread, but programs can run in parallel, if blocking comes
so it will create seprate thread and assigned the blocked task & continue it’s
execution.
Async is non-blocking, which means it will send multiple requests to a server.
In Multithreading Programming
-A thread is a single continuous flow of control within a program.
-Multithreading is a technique where the processor uses multiple threads to execute
multiple processes concurrently.
-In Multithreading every thread has different tasks like
( It’s like different workers has differnet jobs)
In Asynchronous Programming
-Asynchronous programming is about the asynchronous sequence of Tasks,
while multithreading is about multiple threads running in parallel
USE CASE Of Asynchronous
-Asynchronous programming should only be used in programming independent tasks.
1. Responsive UI is a great use case for asynchronous programming.
E.g. In a shopping app. When a user pulls up their order, the font size should
increase. Instead of waiting to load the history and update the font size, asynchronous
programming can make both actions simultaneously.
2. One more example is, It is use to make a call to an API.
where asynchronous functions say, “Get me the data from a website, and when it
gets here, insert that & fetched data back into my script.”
Explore the asynchronous execution support in Spring Step-By-Step
- Here We'll explore the asynchronous execution support in Spring
with the help of @Async & @EnableAsync etc.
- Simply put this annotation on a method of a bean with @Async
then it will make it execute in a separate thread.
OR
In other words, the caller will not wait for the completion of the called method.
Step:1 Enable Async Support
Let's start by enabling asynchronous processing with Java configuration.
-We'll do this by adding the @EnableAsync to a configuration class:
The enable annotation is enough to provide Async support.
By default , @EnableAsync detects Spring's @Async annotation
Or
The @EnableAsync annotation switches on Spring's ability to run @Async methods in a
background thread pool.
Step:2 Put @Async annotation on methods
Annotating a method of a bean with @Async will make it execute in a separate thread.
But We Have Follow Some Rules
Applying @Async Annotation On Types Of Methods
1. Methods With Void Return Type
(This is the simple way to configure a method with void return type
to run asynchronously)
2. Methods With Return Type (By Wrapping The Actual Return In The Future)
A. Methods With Void Return Type
-Here sendTextMessage is a seprate task so spring will create seprate thread
automatically because of @Async method.
B. Methods With Return Type
-Here sayHello is a seprate task so spring will create seprate thread
automatically, because of @Async method & return future object, untill
getting future object first thread will keep continuous searching for result
compilition.
Limitations On @Async annotation
1. It must be applied to public methods only.
2. Self-invocation not allowed.
(calling the async method from within the same class won’t work.)
Reasons-:
-The reasons are simple: The method needs to be public so that it can be proxied.
-And self-invocation doesn't work because it bypasses the proxy and calls the
underlying method directly like NORMAL METHOD.
Here @Async method will not work.
Exception Handling
-When a method return type is a Future, exception handling is easy. Coz
Future.get() method will throw the exception called ExecutionException.
-But if the return type of method is void, exceptions will not be propagated to the
caller thread. So, we need to add extra configurations to handle exceptions.
Extra configuration are like-:
1. First we have to create a custom async exception handler by
implementing AsyncUncaughtExceptionHandler interface.
& Override The handleUncaughtException() method,
which is invoked when any uncaught asynchronous exception will come.
2. After That we have to implement AsyncConfigurer interface in the configuration
class. & We also need to override
the getAsyncUncaughtExceptionHandler() method to return our custom
asynchronous exception handler.
Sample Code Of Exception Handling.
Configuration 1: Implementing AsyncUncaughtExceptionHandler to handle excep.
Configuration 2: Implementing AsyncConfigurer for returning Handler
CONs Of Asynchronous Programming
-It requires a lot of callbacks and recursive functions which might be typical to handle
during development.
-Asynchronous scripting might be difficult to implement in some programming
languages.
-Code can get messy and difficult to debug.
Conclusion
-In this session, we looked running asynchronous code with Spring boot.
-We started with the very basic configuration and annotation to make it work.
-But we also looked at more advanced configurations such as providing our own
executor or exception handling strategies, etc…
Thank You!

More Related Content

Similar to Asynchronous Programming in Spring Framework: A Complete Guide

Android development training programme , Day 3
Android development training programme , Day 3Android development training programme , Day 3
Android development training programme , Day 3DHIRAJ PRAVIN
 
End to-end async and await
End to-end async and awaitEnd to-end async and await
End to-end async and awaitvfabro
 
Drilling the Async Library
Drilling the Async LibraryDrilling the Async Library
Drilling the Async LibraryKnoldus Inc.
 
Unit2-Part2-MultithreadAlgos.pptx.pdf
Unit2-Part2-MultithreadAlgos.pptx.pdfUnit2-Part2-MultithreadAlgos.pptx.pdf
Unit2-Part2-MultithreadAlgos.pptx.pdfVinayak247538
 
Lecture 23-24.pptx
Lecture 23-24.pptxLecture 23-24.pptx
Lecture 23-24.pptxtalha ijaz
 
Asynchronous Programming in .NET
Asynchronous Programming in .NETAsynchronous Programming in .NET
Asynchronous Programming in .NETPierre-Luc Maheu
 
E2E testing Single Page Apps and APIs with Cucumber.js and Puppeteer
E2E testing Single Page Apps and APIs with Cucumber.js and PuppeteerE2E testing Single Page Apps and APIs with Cucumber.js and Puppeteer
E2E testing Single Page Apps and APIs with Cucumber.js and PuppeteerPaul Jensen
 
Capistrano, Puppet, and Chef
Capistrano, Puppet, and ChefCapistrano, Puppet, and Chef
Capistrano, Puppet, and ChefDavid Benjamin
 
No callbacks, No Threads - Cooperative web servers in Ruby 1.9
No callbacks, No Threads - Cooperative web servers in Ruby 1.9No callbacks, No Threads - Cooperative web servers in Ruby 1.9
No callbacks, No Threads - Cooperative web servers in Ruby 1.9Ilya Grigorik
 
Asynchronous programming - .NET Way
Asynchronous programming - .NET WayAsynchronous programming - .NET Way
Asynchronous programming - .NET WayBishnu Rawal
 
Asynchronous programming in ASP.NET
Asynchronous programming in ASP.NETAsynchronous programming in ASP.NET
Asynchronous programming in ASP.NETAlex Thissen
 
Ddd melbourne 2011 C# async ctp
Ddd melbourne 2011  C# async ctpDdd melbourne 2011  C# async ctp
Ddd melbourne 2011 C# async ctpPratik Khasnabis
 
An investigation into Cluster CPU load balancing in the JVM
An investigation into Cluster CPU load balancing in the JVMAn investigation into Cluster CPU load balancing in the JVM
An investigation into Cluster CPU load balancing in the JVMCalum Beck
 
PyCon Canada 2019 - Introduction to Asynchronous Programming
PyCon Canada 2019 - Introduction to Asynchronous ProgrammingPyCon Canada 2019 - Introduction to Asynchronous Programming
PyCon Canada 2019 - Introduction to Asynchronous ProgrammingJuti Noppornpitak
 
End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em...
End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em...End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em...
End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em...Paul Jensen
 
Introduction to Python Asyncio
Introduction to Python AsyncioIntroduction to Python Asyncio
Introduction to Python AsyncioNathan Van Gheem
 

Similar to Asynchronous Programming in Spring Framework: A Complete Guide (20)

C# Async Await
C# Async AwaitC# Async Await
C# Async Await
 
Android development training programme , Day 3
Android development training programme , Day 3Android development training programme , Day 3
Android development training programme , Day 3
 
End to-end async and await
End to-end async and awaitEnd to-end async and await
End to-end async and await
 
Concurrency and parallel in .net
Concurrency and parallel in .netConcurrency and parallel in .net
Concurrency and parallel in .net
 
Designing Better API
Designing Better APIDesigning Better API
Designing Better API
 
Drilling the Async Library
Drilling the Async LibraryDrilling the Async Library
Drilling the Async Library
 
Unit2-Part2-MultithreadAlgos.pptx.pdf
Unit2-Part2-MultithreadAlgos.pptx.pdfUnit2-Part2-MultithreadAlgos.pptx.pdf
Unit2-Part2-MultithreadAlgos.pptx.pdf
 
Lecture 23-24.pptx
Lecture 23-24.pptxLecture 23-24.pptx
Lecture 23-24.pptx
 
Asynchronous Programming in .NET
Asynchronous Programming in .NETAsynchronous Programming in .NET
Asynchronous Programming in .NET
 
E2E testing Single Page Apps and APIs with Cucumber.js and Puppeteer
E2E testing Single Page Apps and APIs with Cucumber.js and PuppeteerE2E testing Single Page Apps and APIs with Cucumber.js and Puppeteer
E2E testing Single Page Apps and APIs with Cucumber.js and Puppeteer
 
Capistrano, Puppet, and Chef
Capistrano, Puppet, and ChefCapistrano, Puppet, and Chef
Capistrano, Puppet, and Chef
 
No callbacks, No Threads - Cooperative web servers in Ruby 1.9
No callbacks, No Threads - Cooperative web servers in Ruby 1.9No callbacks, No Threads - Cooperative web servers in Ruby 1.9
No callbacks, No Threads - Cooperative web servers in Ruby 1.9
 
Asynchronous programming - .NET Way
Asynchronous programming - .NET WayAsynchronous programming - .NET Way
Asynchronous programming - .NET Way
 
Asynchronous programming in ASP.NET
Asynchronous programming in ASP.NETAsynchronous programming in ASP.NET
Asynchronous programming in ASP.NET
 
Ddd melbourne 2011 C# async ctp
Ddd melbourne 2011  C# async ctpDdd melbourne 2011  C# async ctp
Ddd melbourne 2011 C# async ctp
 
An investigation into Cluster CPU load balancing in the JVM
An investigation into Cluster CPU load balancing in the JVMAn investigation into Cluster CPU load balancing in the JVM
An investigation into Cluster CPU load balancing in the JVM
 
PyCon Canada 2019 - Introduction to Asynchronous Programming
PyCon Canada 2019 - Introduction to Asynchronous ProgrammingPyCon Canada 2019 - Introduction to Asynchronous Programming
PyCon Canada 2019 - Introduction to Asynchronous Programming
 
End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em...
End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em...End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em...
End to end testing Single Page Apps & APIs with Cucumber.js and Puppeteer (Em...
 
Async programming in c#
Async programming in c#Async programming in c#
Async programming in c#
 
Introduction to Python Asyncio
Introduction to Python AsyncioIntroduction to Python Asyncio
Introduction to Python Asyncio
 

More from Aayush Chimaniya

More from Aayush Chimaniya (6)

Jasper Reports.pptx
Jasper Reports.pptxJasper Reports.pptx
Jasper Reports.pptx
 
Microservices Api Gateway Eureka Server.pptx
Microservices Api Gateway Eureka Server.pptxMicroservices Api Gateway Eureka Server.pptx
Microservices Api Gateway Eureka Server.pptx
 
MongoDB.pptx
MongoDB.pptxMongoDB.pptx
MongoDB.pptx
 
Java SpringMVC SpringBOOT (Divergent).ppt
Java SpringMVC SpringBOOT (Divergent).pptJava SpringMVC SpringBOOT (Divergent).ppt
Java SpringMVC SpringBOOT (Divergent).ppt
 
SADBlood Bank.pdf
SADBlood Bank.pdfSADBlood Bank.pdf
SADBlood Bank.pdf
 
Electric Vehicle
Electric VehicleElectric Vehicle
Electric Vehicle
 

Recently uploaded

Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerunnathinaik
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxsocialsciencegdgrohi
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 

Recently uploaded (20)

Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developer
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 

Asynchronous Programming in Spring Framework: A Complete Guide

  • 1. Asynchronous Programming In Spring Framework Presented By-: Aayush Chimaniya
  • 2. Contents-: 1. Introduction Of Asynchronous 2. Difference Between SYNC & MULTITHREADING & ASYNC Programming. 3. Diagrammatic Differences 4. How Works Multithreading Programming & Asynchronous Programming 5. USE CASEs Of Asynchronous 6. Explore the asynchronous execution support in Spring Step-By-Step 7. Exception Handling In Asynchronous Programming 8. CONs Of Asynchronous Programming 9. Conclusion
  • 3. INTRODUCTION OF ASYNCHRONOUS PROGRAMMING 1.Asynchronous programming is a form of parallel programming. 2. It allows a unit of work, to run separately from the primary thread. When the work is complete, it notifies to the main thread. 3. It uses the same thread to process multiple requests without any request blocking the thread. 4.Asynchronous programming has actually been around for a long time, but in recent years, it’s become more widely used. 6.It helps to developers to to run applications faster.
  • 5. DIFFERENCE BETWEEN SYNC & MULTITHREADING & ASYNC PROGRAMMING -Sync is single-thread, means one program will run at a time. Sync is blocking pattern, means it can send one request to the server at a time and will wait for, that request to be answered by the server. -Multi-Thread is multi-thread programs, But every thread has assigned seprate task. Multithreading programming is all about concurrent execution of different functions. -Async is multi-thread, but programs can run in parallel, if blocking comes so it will create seprate thread and assigned the blocked task & continue it’s execution. Async is non-blocking, which means it will send multiple requests to a server.
  • 6. In Multithreading Programming -A thread is a single continuous flow of control within a program. -Multithreading is a technique where the processor uses multiple threads to execute multiple processes concurrently. -In Multithreading every thread has different tasks like ( It’s like different workers has differnet jobs) In Asynchronous Programming -Asynchronous programming is about the asynchronous sequence of Tasks, while multithreading is about multiple threads running in parallel
  • 7. USE CASE Of Asynchronous -Asynchronous programming should only be used in programming independent tasks. 1. Responsive UI is a great use case for asynchronous programming. E.g. In a shopping app. When a user pulls up their order, the font size should increase. Instead of waiting to load the history and update the font size, asynchronous programming can make both actions simultaneously. 2. One more example is, It is use to make a call to an API. where asynchronous functions say, “Get me the data from a website, and when it gets here, insert that & fetched data back into my script.”
  • 8. Explore the asynchronous execution support in Spring Step-By-Step - Here We'll explore the asynchronous execution support in Spring with the help of @Async & @EnableAsync etc. - Simply put this annotation on a method of a bean with @Async then it will make it execute in a separate thread. OR In other words, the caller will not wait for the completion of the called method.
  • 9. Step:1 Enable Async Support Let's start by enabling asynchronous processing with Java configuration. -We'll do this by adding the @EnableAsync to a configuration class: The enable annotation is enough to provide Async support. By default , @EnableAsync detects Spring's @Async annotation Or The @EnableAsync annotation switches on Spring's ability to run @Async methods in a background thread pool.
  • 10. Step:2 Put @Async annotation on methods Annotating a method of a bean with @Async will make it execute in a separate thread. But We Have Follow Some Rules Applying @Async Annotation On Types Of Methods 1. Methods With Void Return Type (This is the simple way to configure a method with void return type to run asynchronously) 2. Methods With Return Type (By Wrapping The Actual Return In The Future)
  • 11. A. Methods With Void Return Type -Here sendTextMessage is a seprate task so spring will create seprate thread automatically because of @Async method.
  • 12. B. Methods With Return Type -Here sayHello is a seprate task so spring will create seprate thread automatically, because of @Async method & return future object, untill getting future object first thread will keep continuous searching for result compilition.
  • 13. Limitations On @Async annotation 1. It must be applied to public methods only. 2. Self-invocation not allowed. (calling the async method from within the same class won’t work.) Reasons-: -The reasons are simple: The method needs to be public so that it can be proxied. -And self-invocation doesn't work because it bypasses the proxy and calls the underlying method directly like NORMAL METHOD. Here @Async method will not work.
  • 14. Exception Handling -When a method return type is a Future, exception handling is easy. Coz Future.get() method will throw the exception called ExecutionException. -But if the return type of method is void, exceptions will not be propagated to the caller thread. So, we need to add extra configurations to handle exceptions. Extra configuration are like-: 1. First we have to create a custom async exception handler by implementing AsyncUncaughtExceptionHandler interface. & Override The handleUncaughtException() method, which is invoked when any uncaught asynchronous exception will come. 2. After That we have to implement AsyncConfigurer interface in the configuration class. & We also need to override the getAsyncUncaughtExceptionHandler() method to return our custom asynchronous exception handler.
  • 15. Sample Code Of Exception Handling. Configuration 1: Implementing AsyncUncaughtExceptionHandler to handle excep. Configuration 2: Implementing AsyncConfigurer for returning Handler
  • 16. CONs Of Asynchronous Programming -It requires a lot of callbacks and recursive functions which might be typical to handle during development. -Asynchronous scripting might be difficult to implement in some programming languages. -Code can get messy and difficult to debug.
  • 17. Conclusion -In this session, we looked running asynchronous code with Spring boot. -We started with the very basic configuration and annotation to make it work. -But we also looked at more advanced configurations such as providing our own executor or exception handling strategies, etc…