Lesson 2 · Unit 04
Out of order
Stale replies, and limits on how much runs at once
What you practise
- Responses arrive in any order: the stale search-result bug, "last write wins", fixing it with request ids or cancellation, limiting concurrency with a semaphore
Try a question from this lesson
Pick one
A search box sends a request on every keystroke, and shows whichever reply arrived most recently. The box says "cat". What is on screen after 300 ms?
0 ms types "ca" request A sent
50 ms types "cat" request B sent
150 ms reply B results = B
300 ms reply A results = ACorrect answer
Results for "ca"
Why
Request A was sent first but answered last, and its reply overwrote the newer one. The screen now shows results for text the user is no longer typing.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Last to arrive wins
Replies come back in the order they finish, not the order they were sent. A slow old request can land after a fast new one.
If every reply simply overwrites the same state, the last to arrive wins, however stale it is.
Two fixes: ignore any reply that is not from the newest request, or cancel the old request when a new one starts.
Concept
A limit on how many at once
Starting 5,000 requests in the same instant can get you blocked, or knock the other side over.
A semaphore holds a fixed number of permits. A task takes a permit before it starts and gives it back when it is done. When none are left, the next task waits.
So at most that many tasks are in flight at any moment. It is a pool, for async code.
10 more exercises in the app
- 5× type the answer
- 1× fill the blanks
- 2× true or false
- 2× multiple choice
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.