2. Asynchronous - Definition
● Start a thread and assign a task.
● Get notified once the result is ready
● Process the result
3. Why asynchrony?
● It’s faster
● Use available resources optimally
● Avoid freezing UI - Swing components should be manipulated only via the
event dispatching thread. Offload long running tasks to a separate thread
4. A brief History
● Started with Threads and tasks
● Thread pools and futures
● Completable Future API
5. Multithreading vs asynchronous programming
● Asynchronous programming - mostly stays in a single thread.
● No visibility and atomicity issues
● No synchronization is required
● Thread confinement
● No context switch as it is single threaded
● Async is non-blocking - due to the callbacks
7. Thread per task approach - drawbacks
● Thread lifecycle overhead - creation and teardown cost is high
● Resource consumption - memory
● There’s a limit on number of threads can be created
8. Thread pools
● Manages a homogenous pool of worker threads
● Bound to a work queue holding tasks waiting to be executed
● Decouples task submission from execution
10. Types of thread pools
● Fixed thread pool - grows up to the max size and then keep the pool size
constant
● Cached thread pool - more flexibility to reap idle threads. No bounds on the
pool size
● Single thread executor - Sequential task execution
● Scheduled thread pool - Fixed size thread pool supporting periodic tasks
11. Result bearing tasks
● Callable and future
● Future allows checking whether the task is cancelled, completed, retrieve it’s
results and cancel the task
● Blocking synchronizer - future.get() is blocking !
● Future - bridge between master thread and worker thread executing the task
● Makes chaining of tasks much difficult - need to pass future object around
● Completable future addresses this issue !