01: /**
02: * All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
03: */package com.tc.util.concurrent;
04:
05: /**
06: * This class isn't very exciting, nor is it best (or only) way to implement a (safe) stoppable thread. It is useful to
07: * subclass StoppableThread if need to support stop functionality and you don't want to assume that it's okay to just
08: * interrupt() the thread at any given moment. In my opinion, if the code you're running in the thread isn't entirely in
09: * your control, you probably don't want to randomly interrupt it. For threads that spend most of their time blocking on
10: * something, simply use a timeout and periodically check stopRequested() to see if it is time to stop. <br>
11: * <br>
12: * README: You have to actually check stopRequested() someplace in your run() method for this thread to be "stoppable".
13: */
14: public class StoppableThread extends Thread implements LifeCycleState {
15:
16: private volatile boolean stopRequested = false;
17:
18: public StoppableThread() {
19: super ();
20: }
21:
22: public StoppableThread(Runnable target) {
23: super (target);
24: }
25:
26: public StoppableThread(String name) {
27: super (name);
28: }
29:
30: public StoppableThread(ThreadGroup group, Runnable target) {
31: super (group, target);
32: }
33:
34: public StoppableThread(Runnable target, String name) {
35: super (target, name);
36: }
37:
38: public StoppableThread(ThreadGroup group, String name) {
39: super (group, name);
40: }
41:
42: public StoppableThread(ThreadGroup group, Runnable target,
43: String name) {
44: super (group, target, name);
45: }
46:
47: public StoppableThread(ThreadGroup group, Runnable target,
48: String name, long stackSize) {
49: super (group, target, name, stackSize);
50: }
51:
52: public boolean isStopRequested() {
53: return stopRequested;
54: }
55:
56: public void requestStop() {
57: this .stopRequested = true;
58: }
59:
60: public boolean stopAndWait(long timeout) {
61: requestStop();
62: try {
63: join(timeout);
64: } catch (InterruptedException e) {
65: //
66: }
67: return !isAlive();
68: }
69:
70: }
|