Please enable JavaScript.
Coggle requires JavaScript to display documents.
7.2 Stopping a Thread-Based Service - Coggle Diagram
7.2 Stopping a Thread-Based Service
Overview
Services own threads (e.g., thread pools).
Services typically outlive the method that created them.
Threads must be persuaded to shut down — not forcefully stopped.
Thread ownership:
No formal API ownership, but conceptually the creator “owns” the thread.
Only the owner should manage the thread (interrupt, shut down, etc.).
Application → owns service → which owns threads.
Provide lifecycle methods for thread-owning services.
Logging Service
Logging is common in server apps.
Basic logging: println with PrintWriter (thread-safe).
Multiline logs may need client-side locking to prevent interleaving.
Performance concern in high-volume apps → better to queue logs for another thread.
Cancellation must stop both producers and consumers.
ExecutorService Shutdown
Two shutdown methods:
shutdown() – graceful, waits for tasks to finish.
shutdownNow() – abrupt, cancels running tasks, returns unstarted tasks.
Tradeoff:
Graceful: safer, slower.
Abrupt: faster, risk of inconsistency.
Lifecycle should be encapsulated in higher-level services.
Ownership chain: application → service → ExecutorService → threads.
Poison Pills
Special object put in queue: “Stop signal”.
Ensures consumer finishes all prior tasks.
Used in FIFO queues.
Limitations:
Only works if number of producers/consumers is known.
For N producers → N poison pills.
For M consumers → each producer submits M pills.
Reliable with unbounded queues.
One-Shot Execution Service
Private Executor used in a method that blocks until all tasks are done.
Lifetime of the Executor is bounded by the method.
Methods like invokeAll, invokeAny are helpful.
Limitations of shutdownNow
Cancels running tasks.
Returns list of not-started tasks (may be wrapped Runnables).
Limitation:
Can’t tell which tasks were started but didn’t complete.
No built-in checkpointing.
No shutdown option exists where:
Unstarted tasks are returned.
In-progress tasks are allowed to finish.