Bird
Raised Fist0
Kotlinprogramming~10 mins

Job lifecycle and cancellation in Kotlin - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Job lifecycle and cancellation
Create Job
↓
Start Job
↓
Job Running
↓
Cancel Job?
Yes→Job Cancelling
↓
Job Cancelled
↓
Cleanup
No↓
Job Complete
↓
Job Finished
This flow shows how a Kotlin Job is created, started, runs, can be cancelled, and then finishes or cleans up.
Execution Sample
Kotlin
val job = CoroutineScope(Dispatchers.Default).launch {
    repeat(3) {
        println("Working $it")
        delay(100)
    }
}
job.cancel()
This code starts a job that prints 'Working' three times with delays, but then cancels the job immediately.
Execution Table
StepActionJob StateOutputNotes
1Create job with launchNewJob is created but not started yet
2Job starts runningActiveJob begins execution of coroutine
3Iteration 0: printActiveWorking 0First loop iteration output
4Job.cancel() calledCancellingCancellation requested
5Check cancellation before iteration 1CancellingJob notices cancellation
6Job stops executionCancelledJob stops before printing 'Working 1'
7Job cleanupCancelledResources cleaned up, job finished
8Job is completeCancelledJob lifecycle ends
💡 Job is cancelled during execution, so it stops early and does not complete all iterations.
Variable Tracker
VariableStartAfter Step 3After Step 4After Step 6Final
job.stateNewActiveCancellingCancelledCancelled
loop index (it)N/A0N/AN/AN/A
output"""Working 0\n""Working 0\n""Working 0\n""Working 0\n"
Key Moments - 3 Insights
Why does the job stop printing after 'Working 0'?
Because job.cancel() is called after the first print, the job state changes to Cancelling and then Cancelled, so the loop stops early as shown in steps 4 to 6 in the execution_table.
Is the job immediately stopped when cancel() is called?
No, the job moves to Cancelling state first and checks for cancellation cooperatively before stopping, as seen between steps 4 and 6.
What happens if we don't call cancel()?
The job runs all iterations and finishes normally, moving from Active to Completed state without interruption.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the job state at Step 5?
AActive
BCancelled
CCancelling
DCompleted
💡 Hint
Check the 'Job State' column at Step 5 in the execution_table.
At which step does the job print 'Working 0'?
AStep 2
BStep 3
CStep 4
DStep 6
💡 Hint
Look at the 'Output' column in the execution_table for the printed text.
If cancel() was called after Step 3, what would happen at Step 6?
AJob stops and becomes Cancelled
BJob is still Active
CJob continues running normally
DJob restarts
💡 Hint
Refer to how job.cancel() affects job state between Steps 4 and 6 in the execution_table.
Concept Snapshot
Job lifecycle in Kotlin:
- Create job with launch()
- Job starts in Active state
- Can be cancelled with cancel()
- Cancellation moves job to Cancelling then Cancelled
- Job stops cooperatively on cancellation
- Job finishes in Completed state if not cancelled
Full Transcript
This visual trace shows how a Kotlin Job is created, started, runs a loop printing 'Working' messages, and then is cancelled. The job starts in New state, moves to Active when running, and after cancel() is called, it moves to Cancelling and then Cancelled states. The job stops printing early due to cancellation. Variables like job.state and loop index change step by step. Key moments clarify why the job stops early and how cancellation works cooperatively. Quiz questions test understanding of job states and output timing.

Practice

(1/5)
1. Which of the following best describes the lifecycle of a Kotlin Job?
easy
A. A job is always active and never completes.
B. A job starts cancelled and then becomes active.
C. A job starts active, can be cancelled, and then completes.
D. A job completes before it starts.

Solution

  1. Step 1: Understand Job lifecycle states

    A Kotlin Job begins in an active state, meaning it is running or ready to run.
  2. Step 2: Recognize cancellation and completion

    A Job can be cancelled to stop its work, and after finishing or cancellation, it reaches a completed state.
  3. Final Answer:

    A job starts active, can be cancelled, and then completes. -> Option C
  4. Quick Check:

    Job lifecycle = active -> cancelled -> completed [OK]
Hint: Jobs start active, then cancel or complete [OK]
Common Mistakes:
  • Thinking jobs start cancelled
  • Assuming jobs never complete
  • Confusing job states order
2. Which Kotlin code snippet correctly cancels a job and waits for its completion?
easy
A. job.cancelAndJoin()
B. job.cancel()
C. job.start()
D. job.join()

Solution

  1. Step 1: Identify cancellation with waiting

    The method cancelAndJoin() cancels the job and suspends until it finishes.
  2. Step 2: Differentiate from other methods

    cancel() only requests cancellation without waiting; join() waits but doesn't cancel; start() begins a job.
  3. Final Answer:

    job.cancelAndJoin() -> Option A
  4. Quick Check:

    Cancel and wait = cancelAndJoin() [OK]
Hint: Use cancelAndJoin() to cancel and wait [OK]
Common Mistakes:
  • Using cancel() without waiting
  • Confusing join() with cancel
  • Calling start() to cancel
3. What will be the output of this Kotlin coroutine code?
val job = CoroutineScope(Dispatchers.Default).launch {
    repeat(3) { i ->
        println("Working on $i...")
        delay(100)
    }
}
job.cancel()
Thread.sleep(500)
medium
A. Prints all three "Working on" lines
B. Prints some "Working on" lines before stopping
C. Throws a cancellation exception
D. Prints no output

Solution

  1. Step 1: Analyze job launch and cancellation

    The job starts and prints "Working on 0...", then delays. The cancel() is called immediately after launch.
  2. Step 2: Understand cancellation effect

    Because cancellation happens quickly, some iterations may run before the job stops, so partial output appears.
  3. Final Answer:

    Prints some "Working on" lines before stopping -> Option B
  4. Quick Check:

    Partial output due to quick cancel [OK]
Hint: Cancel stops job but may print partial output [OK]
Common Mistakes:
  • Expecting all lines printed
  • Expecting no output at all
  • Assuming exception is printed
4. Identify the error in this Kotlin coroutine cancellation code:
val job = CoroutineScope(Dispatchers.Default).launch {
    try {
        repeat(5) {
            println("Working...")
            delay(100)
        }
    } catch (e: Exception) {
        println("Cancelled")
    }
}
job.cancelAndJoin()
medium
A. Missing job.start() before cancel
B. cancelAndJoin() should be called inside launch
C. delay() cannot be used inside launch
D. Catching Exception does not handle cancellation properly

Solution

  1. Step 1: Understand cancellation exception type

    Cancellation throws CancellationException, which is a subclass of Throwable but not Exception.
  2. Step 2: Recognize catch block limitation

    Since CancellationException is not caught by catch (e: Exception), the cancellation is not handled as intended.
  3. Final Answer:

    Catching Exception does not handle cancellation properly -> Option D
  4. Quick Check:

    Catch CancellationException, not Exception [OK]
Hint: Catch CancellationException, not Exception [OK]
Common Mistakes:
  • Catching Exception instead of CancellationException
  • Calling cancelAndJoin() incorrectly
  • Thinking delay() is invalid inside launch
5. You want to safely cancel a long-running job and perform cleanup after cancellation. Which Kotlin coroutine pattern achieves this correctly?
hard
A. Use job.cancelAndJoin() then run cleanup code after it returns.
B. Call job.cancel() and immediately start a new job for cleanup.
C. Ignore cancellation and let the job finish naturally.
D. Call job.join() without cancelling, then cleanup.

Solution

  1. Step 1: Understand safe cancellation

    Using cancelAndJoin() cancels the job and waits until it fully stops, ensuring no work is left running.
  2. Step 2: Perform cleanup after cancellation

    After cancelAndJoin() returns, it's safe to run cleanup code because the job is fully cancelled.
  3. Final Answer:

    Use job.cancelAndJoin() then run cleanup code after it returns. -> Option A
  4. Quick Check:

    Cancel and wait before cleanup = cancelAndJoin() [OK]
Hint: Cancel and wait before cleanup with cancelAndJoin() [OK]
Common Mistakes:
  • Starting cleanup before job stops
  • Ignoring cancellation
  • Using join() without cancelling
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard