Part 0 - Asynchronous Vs Synchronous Programming
Part 0 - Asynchronous Vs Synchronous Programming
vs
Synchronous
Course Materials
iteratrlearning.com/async-exercises.zip
iteratrlearning.com/async-slides-1.zip
Introduction
Approaches
Programming Styles
SOA and Microservices
● Increasingly popular style of application development
Thread 1
Thread 2
Queue
….
One thread per request
E.g. MortgageServlet
Common Threading Model
● Used by Servlets and anything that sits on them
○ Spring
○ Jersey
● JDBC
○ Pool within JDBC connector of threads talking to DB.
○ Often hard to work around this limitation
Quiz: What problems can you think
of with this approach?
Latency
latency
● Context Switching
○ OS Scheduler
○ Interruptions
● Locality of reference
○ Cache locality usually the main cost of context switching
Example Asynchrony App
Account Service
Bank
Credit Checking
Service
Introduction to Non-Blocking I/O
Blocking vs Non-blocking I/O
Blocking I/O
● The process performing I/O blocks until the operation is complete
● Need as many threads as concurrent I/O operations
● Scalability issues: spend all your time flipping between threads
● Often simpler to program and debug
Non-Blocking I/O
From:
https://github.com/Netflix-Skunkworks/WSPerfLab/blob/master/test-results/RxNetty_vs_Tomcat_April2
015.pdf
To the asynchronous Bank Account
Service!
The I/O Stack
Application Code
Servlet Container
NIO
● How do you split a problem into discrete steps and then pass values
between those steps?
Callbacks
● Fundamental primitive of asynchronous programming.
● Where you register your callback can now control its threading model
The Callback Transformation
Result result = otherSystemComponent.performOperation();
otherSystemComponent.performOperation(result ->
});
// Eg: AsyncCurrentAccountServlet
Exercise
● Implement a new asynchronous service
○ Grant a mortgage if
■ Requested amount to borrow <= 4 * current account balance
○ Return SC_OK (200) if granting mortgage, SC_FORBIDDEN (403)
otherwise
com.iteratrlearning.problems.asynchronous.SimpleMortgageApplicationServiceTest
Composing Callbacks
● Callbacks can compose - but it’s not that easy
Eg: AsyncMortgageServlet
Summary
● Register callbacks to receive responses asynchronously.
● To compose callbacks
○ create some kind of stateful handler object.
○ Have a method to for each event you want to receive
○ Emit event once you’ve got all the required state.
Summary
Summary
context.setTimeout(5000L);
AsyncHttpClient Timeouts
AsyncHttpClient client = …
client.setRequestTimeout(5000L);
Example
● Modify your MortgageApplicationServlet to retry the getBalance()
○ Retry 10 times then if things are still going wrong return Internal
Server Error (500)
com.iteratrlearning.problems.asynchronous.RetryingMortgageApplicationServiceTest