KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > exolab > jms > common > threads > ThreadPoolWorker


1 /**
2  * Redistribution and use of this software and associated documentation
3  * ("Software"), with or without modification, are permitted provided
4  * that the following conditions are met:
5  *
6  * 1. Redistributions of source code must retain copyright
7  * statements and notices. Redistributions must also contain a
8  * copy of this document.
9  *
10  * 2. Redistributions in binary form must reproduce the
11  * above copyright notice, this list of conditions and the
12  * following disclaimer in the documentation and/or other
13  * materials provided with the distribution.
14  *
15  * 3. The name "Exolab" must not be used to endorse or promote
16  * products derived from this Software without prior written
17  * permission of Exoffice Technologies. For written permission,
18  * please contact info@exolab.org.
19  *
20  * 4. Products derived from this Software may not be called "Exolab"
21  * nor may "Exolab" appear in their names without prior written
22  * permission of Exoffice Technologies. Exolab is a registered
23  * trademark of Exoffice Technologies.
24  *
25  * 5. Due credit should be given to the Exolab Project
26  * (http://www.exolab.org/).
27  *
28  * THIS SOFTWARE IS PROVIDED BY EXOFFICE TECHNOLOGIES AND CONTRIBUTORS
29  * ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
30  * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
31  * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
32  * EXOFFICE TECHNOLOGIES OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
33  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
34  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
35  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
36  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
37  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
38  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
39  * OF THE POSSIBILITY OF SUCH DAMAGE.
40  *
41  * Copyright 2000-2004 (C) Exoffice Technologies Inc. All Rights Reserved.
42  *
43  * $Id: ThreadPoolWorker.java,v 1.1 2004/11/26 01:50:35 tanderson Exp $
44  */

45 package org.exolab.jms.common.threads;
46
47 import org.apache.commons.logging.Log;
48 import org.apache.commons.logging.LogFactory;
49
50 import org.exolab.jms.common.util.FifoQueue;
51
52
53 /**
54  * This class creates an internal thread, adds it to the idleThread queue
55  * and starts it running. The thread will then block on an internal queue
56  * waitUntilWork for a runnable object to be passed to it. Once invoked
57  * the thread will then call the objects run method.
58  *
59  * @version $Revision: 1.1 $ $Date: 2004/11/26 01:50:35 $
60  * @author <a HREF="mailto:mourikis@exolab.org">Jim Mourikis</a>
61  * @see ThreadPool
62  * @see FifoQueue
63  */

64 class ThreadPoolWorker {
65
66     /**
67      * The thread group that this worker is a member of
68      */

69     private ThreadGroup JavaDoc _group;
70
71     /**
72      * A reference to the idle work queue for this ThreadPool.
73      */

74     private FifoQueue _idleWorkers;
75
76     /**
77      * Used to make the thread block until there is something to do. Runnable
78      * objects are passed to the thread in a thread safe manner through
79      * this queue.
80      */

81     private FifoQueue _waitUntilWork;
82
83     /**
84      * The worker thread
85      */

86     private Thread JavaDoc _worker;
87
88     /**
89      * An internal flag used to notify the thread to stop nicely
90      */

91     private volatile boolean _noStopRequested;
92
93     /**
94      * The logger
95      */

96     private static final Log _log = LogFactory.getLog(ThreadPoolWorker.class);
97
98     /**
99      * The constructor creates the worker thread and runs it.
100      * The new thread is given a unique id and added to the idle work queue.
101      * The thread will then sleep until it is allocated work.
102      *
103      * @param group the thread group that the worker is a member of
104      * @param name the name of the thread. This must be unique.
105      * @param idleWorkers a reference to the idle worker queue
106      */

107     public ThreadPoolWorker(ThreadGroup JavaDoc group, String JavaDoc name,
108                             FifoQueue idleWorkers) {
109         _group = group;
110         _idleWorkers = idleWorkers;
111
112         // Note: Only 1 item is allowed in this queue.
113
_waitUntilWork = new FifoQueue(1);
114         _noStopRequested = true;
115
116         Runnable JavaDoc r = new Runnable JavaDoc() {
117             public void run() {
118                 try {
119                     runWork();
120                 } catch (Exception JavaDoc exception) {
121                     _log.error("Thread " + _worker.getName()
122                                + ": terminating on exception", exception);
123                 }
124             }
125         };
126
127         // Create the new internal thread and start it all off.
128
_worker = new Thread JavaDoc(_group, r, name);
129         _worker.setDaemon(_group.isDaemon());
130         _worker.start();
131     }
132
133     /**
134      * This method passes an external runnable object to a waiting thread.
135      * The thread is woken up and begins to run.
136      *
137      * @param target the target to run
138      * @throws InterruptedException If this thread is interrupted externally
139      */

140     public void process(Runnable JavaDoc target) throws InterruptedException JavaDoc {
141         _waitUntilWork.add(target);
142     }
143
144     /**
145      * The thread is requested to stop.
146      * Set the flag and issue an interrupt request.
147      */

148     public void stopRequest() {
149         _noStopRequested = false;
150         _worker.interrupt();
151     }
152
153     /**
154      * Determines if the thread is still alive.
155      *
156      * @return <code>true</code> if the thread is still alive
157      */

158     public boolean isAlive() {
159         return _worker.isAlive();
160     }
161
162     /**
163      * The thread's main loop. A thread begins to run here and blocks until
164      * a runnable object is passed to it via the waitUntilWork queue.
165      */

166     private void runWork() {
167         while (_noStopRequested) {
168             try {
169                 // Worker is ready work. This will never block since the
170
// idleWorker queue has enough capacity for all of
171
// the workers.
172
_idleWorkers.add(this);
173
174                 // wait here until the server allocates work
175
Runnable JavaDoc r = (Runnable JavaDoc) _waitUntilWork.get();
176
177                 runIt(r);
178             } catch (InterruptedException JavaDoc exception) {
179                 Thread.currentThread().interrupt(); // re-assert
180
}
181         }
182     }
183
184     /**
185      * The thread runs here, passing control to the external Runnable
186      * object.
187      *
188      * @param r the target to run
189      */

190     private void runIt(Runnable JavaDoc r) {
191         try {
192             r.run();
193         } catch (Exception JavaDoc exception) {
194             // catch any and all exceptions
195
_log.error("Thread " + _worker.getName()
196                        + ": uncaught exception fell through from run()",
197                        exception);
198         } finally {
199             // Clear the interrupted flag (in case it comes back set)
200
// so that if the loop goes again, the
201
// _waitUntilWork.get() does not mistakenly throw
202
// an InterruptedException.
203
Thread.interrupted();
204         }
205     }
206
207 }
208
Popular Tags