Java Reference
In-Depth Information
creases the task's responsiveness to cancellation: not only can it safely call interruptible
blocking methods while remaining responsive to cancellation, but it can also call blocking
socket I/O methods.
7.2. Stopping a Thread-based Service
Applications commonly create services that own threads, such as thread pools, and the life-
time of these services is usually longer than that of the method that creates them. If the ap-
plication is to shut down gracefully, the threads owned by these services need to be termin-
ated. Since there is no preemptive way to stop a thread, they must instead be persuaded to
shut down on their own.
Sensible encapsulation practices dictate that you should not manipulate a thread—interrupt it,
modify its priority, etc.—unless you own it. The thread API has no formal concept of thread
ownership: a thread is represented with a Thread object that can be freely shared like any
other object. However, it makes sense to think of a thread as having an owner, and this is usu-
ally the class that created the thread. So a thread pool owns its worker threads, and if those
threads need to be interrupted, the thread pool should take care of it.
As with any other encapsulated object, thread ownership is not transitive: the application may
own the service and the service may own the worker threads, but the application doesn't own
the worker threads and therefore should not attempt to stop them directly. Instead, the ser-
vice should provide lifecycle methods for shutting itself down that also shut down the owned
threads; then the application can shut down the service, and the service can shut down the
threads. ExecutorService provides the shutdown and shutdownNow methods; oth-
er thread-owning services should provide a similar shutdown mechanism.
Provide lifecycle methods whenever a thread-owning service has a lifetime longer than that
of the method that created it.
7.2.1. Example: A Logging Service
Most server applications use logging, which can be as simple as inserting println state-
ments into the code. Stream classes like PrintWriter are thread-safe, so this simple ap-
proach would require no explicit synchronization. [3] However, as we'll see in Section 11.6 ,
inline logging can have some performance costs in highvolume applications. Another altern-
ative is have the log call queue the log message for processing by another thread.
Search WWH ::




Custom Search