FREE Subscription to Dr. Dobb’s Digest: Same Great Content, New Digital Edition
Site Archive (Complete)
Java
Email
Print
Reprint

add to:
Del.icio.us
Digg
Google
Furl
Slashdot
Y! MyWeb
Blink
August 02, 2006

Multithreading, Java, & OSGi

(Page 7 of 10)

Interrupt After Run

It is also possible for interrupt() to be called after run() has exited. ThreadManager.stopAll() could check to see if run() has exited before calling interrupt(), but by the time the call to interrupt() actually happens, run() may have exited. In practice, most interrupt() methods perform idempotent actions, such as closing streams. Usually, no special code is required to properly handle this case.

Interrupting the Right Thread

If your interrupt() method does use Thread.interrupt(), you'll need a handle on the thread running the run() method. This is another case where synchronization between run() and interrupt() is necessary—you can't interrupt a thread before it has been created. Here, however, ThreadManager really can help you out.

Interruptible defines a method called getRunThread() that returns the thread on which run() has been (or will be) invoked. This is why Interruptible is an abstract class, and not an interface.

The implementation depends on the private field runThread being assigned exactly once when the thread is created. Callers to getRunThread() block until the assignment occurs. ThreadManager arranges to perform this assignment but the field should not otherwise be visible, even to derived classes implementing Interruptible. This is why Interruptible is a nested class within ThreadManager.

To set the runThread field, ThreadManager leverages the nested ManagedRunnable class, mentioned earlier. ManagedRunnable has its own run() method that sets runThread and calls notifyAll() before invoking Interruptible.run().

Previous Page | 1 Multithreading in Java & OSGi | 2 Requirements | 3 The Challenge | 4 Problem Solving | 5 ThreadManager Design Points | 6 Multiple Blockers | 7 Interrupt After Run | 8 Interrupt Me Before I Run Again | 9 Interrupted Exceptions | 10 Conclusion Next Page
TOP 5 ARTICLES
No Top Articles.



MICROSITES
FEATURED TOPIC

ADDITIONAL TOPICS

INFO-LINK