Async / Await at the Gym

hocHo
2 min readAug 2, 2016

--

In the gym threads are to weights, as tasks are to exercises …

You stride into the gym and head straight to the free weights area. Your eyes scan the weight rack for the 40 lb. dumbbells but all the slots are empty. You glance around, resigned to wait.

Task waits for the next free thread, from the thread pool.

A svelte young thing, daintily deposits the dumbbells on the rack and saunters off; nary a glance in your direction.

A thread is now available.

You hurry, eagerly grab the weights and start on bicep curls.

Task starts executing on the thread.

Lactic acid starts kicking in and you reach failure point. You need to rest before your next set. A thought crosses your mind … just drop the weights on the floor, and stand there till you recover.

Potential synchronous task just hogging the thread, waiting for IO to complete.

But like a good gym goer, you reluctantly shuffle along and place the dumbbells on the rack. You pace around; recovering.

Thread returns to the thread pool, task awaits IO to complete.

Swift hands, pick up the dumbbells just racked.

Returned thread, pulled out of the thread pool, begins servicing another task.

You have recovered but no dumbbells are in sight. You wait… Moments later the other pair of 40 lb. dumbbells appear on the rack, thanks to that beefy dude finishing his workout. You have the weights now.

After awaiting, task resumes executing on another thread.

You complete your second set and are through with the dumbbells. You place them on the rack, for other users and head off.

Task completes and the thread returns to the thread pool. There will be more tasks for that thread to service.

Racking weights while you recover, allows more gym members to work out with a lesser number of weights, but with the added inconvenience of racking and unracking the weights.

Tasks which make asynchronous IO calls and are run asynchronously, provide more throughput with the same number of thread, at the cost of thread management and context switching.

If there are more weights than gym members and/or the recovery period is relatively short and/or the workout time needs to be as short as possible, holding on to the weights between sets is acceptable and possibly optimal.

Synchronous tasks are ideal when thread demand is low and/or IO waiting periods are short and/or low latency is of utmost importance.

--

--