KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > enterprise > util > threadpool > FastThreadPool


1 /*
2  * The contents of this file are subject to the terms
3  * of the Common Development and Distribution License
4  * (the License). You may not use this file except in
5  * compliance with the License.
6  *
7  * You can obtain a copy of the license at
8  * https://glassfish.dev.java.net/public/CDDLv1.0.html or
9  * glassfish/bootstrap/legal/CDDLv1.0.txt.
10  * See the License for the specific language governing
11  * permissions and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL
14  * Header Notice in each file and include the License file
15  * at glassfish/bootstrap/legal/CDDLv1.0.txt.
16  * If applicable, add the following below the CDDL Header,
17  * with the fields enclosed by brackets [] replaced by
18  * you own identifying information:
19  * "Portions Copyrighted [year] [name of copyright owner]"
20  *
21  * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
22  */

23
24 //NOTE: Tabs are used instead of spaces for indentation.
25
// Make sure that your editor does not replace tabs with spaces.
26
// Set the tab length using your favourite editor to your
27
// visual preference.
28

29 /*
30  * Filename: FastThreadPool.java
31  *
32  * Copyright 2000-2001 by iPlanet/Sun Microsystems, Inc.,
33  * 901 San Antonio Road, Palo Alto, California, 94303, U.S.A.
34  * All rights reserved.
35  *
36  * This software is the confidential and proprietary information
37  * of iPlanet/Sun Microsystems, Inc. ("Confidential Information").
38  * You shall not disclose such Confidential Information and shall
39  * use it only in accordance with the terms of the license
40  * agreement you entered into with iPlanet/Sun Microsystems.
41  */

42
43 /**
44  * <BR> <I>$Source: /cvs/glassfish/appserv-commons/src/java/com/sun/enterprise/util/threadpool/FastThreadPool.java,v $</I>
45  * @author $Author: tcfujii $
46  * @version $Revision: 1.3 $ $Date: 2005/12/25 04:12:32 $
47  */

48
49 package com.sun.enterprise.util.threadpool;
50
51 import java.util.Properties JavaDoc;
52
53 import com.sun.enterprise.util.threadpool.Servicable;
54 import com.sun.enterprise.util.collection.BlockingQueue;
55 import com.sun.enterprise.util.collection.QueueClosedException;
56 import com.sun.enterprise.util.collection.TooManyTasksException;
57 import com.sun.enterprise.util.pool.Pool;
58 import com.sun.enterprise.util.pool.AbstractPool;
59 import com.sun.enterprise.util.pool.BoundedPool;
60 import com.sun.enterprise.util.pool.ObjectFactory;
61
62 import com.sun.enterprise.util.collection.DListNode;
63 //Bug 4677074 begin
64
import java.util.logging.Logger JavaDoc;
65 import java.util.logging.Level JavaDoc;
66 import com.sun.logging.LogDomains;
67 //Bug 4677074 end
68

69 /**
70  * This implementation runs a thread and does the following:
71  * a) Picks a task from the task queue
72  * b) Removes one thread from the (thread)Pool.
73  * c) notifies the threadPoolThread.
74  */

75 public class FastThreadPool {
76     
77 //Bug 4677074 begin
78
static Logger JavaDoc _logger=LogDomains.getLogger(LogDomains.UTIL_LOGGER);
79 //Bug 4677074 end
80
protected boolean bDebug = false;
81     private PoolProperties poolProps;
82     private TaskQueue taskQueue;
83     private int waitCount = 0;
84     private int totalThreadCreatedCount = 0; // 4682740
85
private int totalThreadDestroyedCount = 0; // 4682740
86
private int numMessages = 0;
87     
88     public FastThreadPool(String JavaDoc threadGroupName, int minThreadCount, int maxThreadCount,
89             long maxIdleTime, int queueLimit, TaskFactory factory) {
90         this(new ThreadGroup JavaDoc(threadGroupName), minThreadCount, maxThreadCount,
91                 maxIdleTime, new TaskQueue(queueLimit, factory));
92     }
93     
94     public FastThreadPool(ThreadGroup JavaDoc threadGroup, int minThreadCount, int maxThreadCount,
95             long maxIdleTime, int queueLimit, TaskFactory factory) {
96         this(threadGroup, minThreadCount, maxThreadCount, maxIdleTime,
97                 new TaskQueue(queueLimit, factory));
98     }
99     
100     public FastThreadPool(ThreadGroup JavaDoc threadGroup, int minThreadCount, int maxThreadCount,
101             long maxIdleTime, TaskQueue queue) {
102         this.taskQueue = queue;
103         
104         poolProps = new PoolProperties(minThreadCount, maxThreadCount,
105                 maxIdleTime, taskQueue, threadGroup);
106         
107     }
108     
109     /**
110      * Start the threadpool. Needed for scenarios where the queue gets
111      * created and set in the threadpool from some other object.
112      */

113     public void start() {
114         // We set createdCount to be the number of threads we are creating
115
poolProps.createdCount = poolProps.minThreadCount;
116         for (int i=0; i < poolProps.minThreadCount; i++) {
117             // if (bDebug) System.out.println("FastThreadPool creating thread: "
118
// + i + "/" + poolProps.minThreadCount);
119
//Bug 4677074 begin
120
// if (com.sun.enterprise.util.logging.Debug.enabled) _logger.log(Level.FINE,"FastThreadPool creating thread: "+ i + "/" + poolProps.minThreadCount);
121
//Bug 4677074 end
122
new ThreadPoolThread(poolProps);
123         }
124         // START OF IASRI 4682740
125
com.sun.enterprise.util.MonitorTask.addORBMonitorable(this);
126         // END OF IASRI 4682740
127
}
128     
129     /**
130      * returns the task queue
131      */

132     public TaskQueue getTaskQueue() {
133         return taskQueue;
134     }
135     
136     /**
137      * sets the task queue. Returns true if successful
138      */

139     public boolean setTaskQueue(TaskQueue bq) {
140         if (taskQueue != null)
141             return false;
142         taskQueue = bq;
143         return true;
144     }
145     
146     /**
147      * Add to the head of the queue. Probably a high priority job?
148      */

149     public void addFirst(Servicable servicable)
150             throws TooManyTasksException, QueueClosedException {
151         taskQueue.addFirst(servicable);
152     }
153     
154     /**
155      * Add to the tail of the queue.
156      */

157     public void addLast(Servicable servicable)
158             throws TooManyTasksException, QueueClosedException {
159         taskQueue.addLast(servicable);
160     }
161     
162     /**
163      * Add the job at the specified position. Probably based on priority?
164      */

165     public void add(int index, Servicable servicable)
166             throws TooManyTasksException, QueueClosedException {
167         taskQueue.add(index, servicable);
168     }
169     
170     public void shutdown() {
171         taskQueue.shutdown();
172     }
173     
174     public void abort() {
175         taskQueue.abort();
176     }
177     
178     public int getPoolSize() {
179         return (poolProps != null) ? (poolProps.createdCount) : -1;
180     }
181     
182     public int getWaitCount() {
183         return waitCount;
184     }
185     
186     public int[] getMonitoredValues() {
187         synchronized(poolProps) {
188             // Return the two integer values as an array.
189
int [] ret = {(poolProps != null) ? (poolProps.createdCount) : -1,
190                     waitCount};
191             return ret;
192         }
193     }
194     
195     // Start 4682740 - ORB to support standalone monitoring
196

197     /**
198      * Great for monitoring. All methods used here are unsynchronized.
199      */

200     public String JavaDoc toString() {
201         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
202         sb.append("FastThreadPool [CS=").append(poolProps.createdCount);
203         sb.append(", TC=").append(totalThreadCreatedCount);
204         sb.append(", TD=").append(totalThreadDestroyedCount);
205         sb.append(", Min=").append(poolProps.minThreadCount);
206         sb.append(", Max=").append(poolProps.maxThreadCount);
207         sb.append(", MaxIdle=").append(poolProps.maxIdleTime);
208         sb.append(", Msgs=").append(numMessages);
209         sb.append("]");
210         return sb.toString();
211     }
212     
213     // End 4682740 - ORB to support standalone monitoring
214

215     private class PoolProperties {
216         int minThreadCount;
217         int maxThreadCount;
218         long maxIdleTime;
219         TaskQueue taskQueue;
220         ThreadGroup JavaDoc threadGroup;
221         
222         int createdCount;
223         
224         PoolProperties(int minThreadCount, int maxThreadCount, long maxIdleTime,
225                 TaskQueue taskQueue, ThreadGroup JavaDoc threadGroup) {
226             this.minThreadCount = minThreadCount;
227             this.maxThreadCount = maxThreadCount;
228             this.maxIdleTime = maxIdleTime;
229             this.taskQueue = taskQueue;
230             this.threadGroup = threadGroup;
231             
232             this.createdCount = 0;
233         }
234     }
235     
236     private class ThreadPoolThread implements Runnable JavaDoc {
237         PoolProperties poolProps;
238         
239         ThreadPoolThread(PoolProperties poolProps) {
240             this.poolProps = poolProps;
241             Thread JavaDoc thread = new Thread JavaDoc(poolProps.threadGroup, this);
242             if (poolProps.threadGroup != null) {
243                 if (poolProps.threadGroup.isDaemon()) {
244                     thread.setDaemon(true);
245                 }
246             }
247             thread.start();
248             totalThreadCreatedCount++; // 4682740
249
}
250         
251         public void run() {
252             Servicable task = null;
253             try {
254                 while (true) {
255                     boolean canCreateBuddy = false;
256                     
257                     do {
258                         synchronized (poolProps) {
259                             waitCount++;
260                         }
261                         
262                         task = null; // Bug 4700462 - Intermittent objects hang on to threads blocked on queue
263

264                         task = (Servicable) taskQueue.remove(poolProps.maxIdleTime);
265                         synchronized (poolProps) {
266                             waitCount--;
267                             if (task == null) {
268                                 // We timedout!!
269
if (poolProps.createdCount > poolProps.minThreadCount) {
270                                     //there are too many threads and the system is idle.
271
// if (bDebug) System.out.println(Thread.currentThread().getName()
272
// + " Timedout. (quitting)....");
273
//Bug 4677074 begin
274
// if (com.sun.enterprise.util.logging.Debug.enabled) _logger.log(Level.FINE,Thread.currentThread().getName()+ " Timedout. (quitting)....");
275
//Bug 4677074 end
276
// DIE!!!!
277
poolProps.createdCount--;
278                                     totalThreadDestroyedCount++; // 4682740
279
return;
280                                 }
281                                 // We get to live a little longer!
282
continue;
283                             }
284                             canCreateBuddy = (waitCount == 0) &&
285                                     (poolProps.createdCount < poolProps.maxThreadCount);
286                             // Increment createdCount in anticipation of buddy creation
287
if (canCreateBuddy) poolProps.createdCount++;
288                             numMessages++;
289                         }
290                         if (canCreateBuddy) {
291                             // if (bDebug) System.out.println(Thread.currentThread().getName()
292
// + " creating buddy...");
293
//Bug 4677074 begin
294
// if (com.sun.enterprise.util.logging.Debug.enabled) _logger.log(Level.FINE,Thread.currentThread().getName()+ " creating buddy...");
295
//Bug 4677074 end
296
new ThreadPoolThread(poolProps);
297                         }
298
299                         // if (bDebug) System.out.println(Thread.currentThread().getName()
300
// + " got a task: " + task);
301
//Bug 4677074 begin
302
// if (com.sun.enterprise.util.logging.Debug.enabled) _logger.log(Level.FINE,Thread.currentThread().getName() + " got a task: " + task);
303
//Bug 4677074 end
304
try {
305                             task.prolog();
306                             task.service();
307                             task.epilog();
308                         } catch (Throwable JavaDoc th) {
309 //Bug 4677074 th.printStackTrace();
310
//Bug 4677074 begin
311
_logger.log(Level.SEVERE,"iplanet_util.generic_exception",th);
312 //Bug 4677074 end
313
}
314                     } while (task != null);
315                 }
316             } catch (com.sun.enterprise.util.collection.QueueClosedException qcEx) {
317 //Bug 4677074 System.out.println("Queue closed. Exitting....");
318
//Bug 4677074 begin
319
_logger.log(Level.FINE,"Queue closed. Exitting....");
320 //Bug 4677074 end
321
synchronized (poolProps) {
322                     poolProps.createdCount--;
323                 }
324                 totalThreadDestroyedCount++; // 4682740
325
return;
326             } catch (InterruptedException JavaDoc inEx) {
327 //Bug 4677074 System.out.println("Interrupted. Exitting....");
328
//Bug 4677074 begin
329
_logger.log(Level.SEVERE,"iplanet_util.generic_exception",inEx);
330 //Bug 4677074 end
331
synchronized (poolProps) {
332                     poolProps.createdCount--;
333                 }
334                 totalThreadDestroyedCount++; // 4682740
335
return;
336             }
337         }
338         
339     }
340     
341     
342 }
343
Popular Tags