Job Highlight
Job is the primary mechanism for controlling cancellation behavior of co-routines.
Job - provides another avenue of stopping work other than traditional exception flow. Separate cancellation mechanism that is not as apparent as typical exceptions, where failed co-routine cancel's all co-routines that are related to it through Job hierarchy. (Note: Supervisor-Job is exception)
In ALL scopes that use Regular Job:
- Uncaught, non-cancellation exception → Cancels Siblings + Propagates recursively through parent Job hierarchy, with each parent shutting down its children, Effectively shutting down the entire hierarchy up to the top most Job (or up to where you caught exception at error boundary).
- Cancels siblings: Cancellation Cooperative Functions/suspension point in sibling functions will throw CancellationException
- Propagates to parent: Parent scope will rethrow the original exception that was thrown in co-routine.
Highlight
Job - provide another avenue of stopping work other than traditional exceptions. Separate cancellation mechanism that is not as apparent as typical exception flow, where failed co-routine cancel's all co-routines that are related to it through Job hierarchy.
- Each coroutine has its own Job instance.
- Each Job instance is tied to it's parent job (if it has a parent Job). This tie in enables cancellation behavior.
Example
If regular Job()
were used. If Coroutine#6 throws non-CancellationException exception the entire hierarchy is gonig to be cancelled and Coroutine#1 will rethrow the exception that Coroutine#6 threw.
Creating Error Boundary
- Look at Coroutine scope function and Error Boundary to create error/ boundaries which allows us to try/catch exceptions stopping them from going higher up.
Gotchas
- ⚠️ Firstly, make sure to understand intended Exception/Cancellation Behavior with Regular Job ⚠️.
- ⚠️ Swallowing cancellation exception prevents cancellation ⚠️
- ⚠️ Unhandled exception from async can go to parent scope without going through await() ⚠️
- ⚠️ cancel() call stops on next suspension point, NOT right away ⚠️
- ⚠️ join() does NOT rethrow ⚠️
Backlinks