File: ThreadPool.java

package info (click to toggle)
libgroboutils-java 5-3
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 9,396 kB
  • ctags: 11,186
  • sloc: java: 59,748; xml: 12,762; sh: 377; perl: 104; makefile: 20
file content (379 lines) | stat: -rw-r--r-- 10,667 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
/*
 * @(#)ThreadPool.java      0.9.0 06/04/2000 - 15:13:54
 *
 * Copyright (C) 2000,,2003 2002 Matt Albrecht
 * groboclown@users.sourceforge.net
 * http://groboutils.sourceforge.net
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a
 *  copy of this software and associated documentation files (the "Software"),
 *  to deal in the Software without restriction, including without limitation
 *  the rights to use, copy, modify, merge, publish, distribute, sublicense,
 *  and/or sell copies of the Software, and to permit persons to whom the 
 *  Software is furnished to do so, subject to the following conditions:
 *
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software. 
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL 
 *  THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 
 *  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
 *  DEALINGS IN THE SOFTWARE.
 */

package net.sourceforge.groboutils.util.thread.v1;


import net.sourceforge.groboutils.util.datastruct.v1.SynchQueue;

import java.util.Vector;


/**
 * A pool of QueueThread instances, each containing an instance of
 * an ObjectListener implemented class.  The Class to be the listener
 * is passed into the constructor.  Requirements for the Class are:
 * 1. it implements QueueThread.ObjectListener, 2. it has a public
 * constructor without any parameters.
 * <P>
 * The pool handles menial tasks such as:
 * <ol>
 *      <li>Growing the thread pool if the number of waiting objects
 *          is above a threshold number, up to a maximum number of
 *          threads.
 *      <li>Finding the thread with the fewest number of waiting objects.
 *      <li>Optimization of determining which thread to pass events to.
 * </ol>
 * <P>
 * The pool gets much of its functionality by sharing a single SynchQueue
 * between all of its threads.
 *
 * @author   Matt Albrecht <a href="mailto:groboclown@users.sourceforge.net">groboclown@users.sourceforge.net</a>
 * @since    June 4, 2000
 * @version  $Date: 2003/02/10 22:52:49 $
 */
public class ThreadPool
{
    //----------------------------
    // Public data
    
    
    //----------------------------
    // Private data
    
    private Class m_objListenerClass = null;
    private Object m_objListenerInitData = null;
    
    private QueueThread[] m_pool = null;
    private SynchQueue m_sharedQueue = new SynchQueue();
    
    private int m_maxThreads = 10;
    private int m_numThreads = 0;
    private int m_depthThreshold = 5;
    
    //----------------------------
    // constructors
    
    /**
     * Default constructor
     */
    public ThreadPool( Class objectListenerClass )
    {
        this( objectListenerClass, null, 1, 10 );
    }
    
    
    /**
     * 
     */
    public ThreadPool( Class objectListenerClass, int maxThreads )
    {
        this( objectListenerClass, null, 1, maxThreads );
    }
    
    
    /**
     *
     * @param initData if the given objectListenerClass is an instance
     *      of ThreadObjectListener, then the initData will be passed
     *      into the initialize( Object ) method.
     */
    public ThreadPool( Class objectListenerClass, Object initData )
    {
        this( objectListenerClass, initData, 1, 10 );
    }
    
    
    /**
     * 
     */
    public ThreadPool( Class objectListenerClass, Object initData,
            int maxThreads )
    {
        this( objectListenerClass, initData, 1, maxThreads );
    }
    
    
    /**
     * 
     */
    public ThreadPool( Class objectListenerClass, Object initData,
            int startingThreadCount, int maxThreads )
    {
        this.m_objListenerClass = objectListenerClass;
        this.m_objListenerInitData = initData;
        try
        {
            createObjectListenerInstance();
        }
        catch (Exception ex)
        {
ex.printStackTrace();
            throw new IllegalArgumentException( "Class "+objectListenerClass+
                " does not create ObjectListener instances");
        }
        
        setMaximumThreadCount( maxThreads );
        this.m_pool = new QueueThread[ maxThreads ];
        while (this.m_numThreads < startingThreadCount)
        {
            addNewThread();
        }
    }
    
    
    //----------------------------
    // Public methods
    
    /**
     * 
     */
    public void setDepthThreshold( int threshold )
    {
        if (threshold < 1)
        {
            throw new IllegalArgumentException("threshold "+threshold+
                " is too low");
        }
        this.m_depthThreshold = threshold;
    }
    
    /**
     * 
     */
    public int getObjectDepth()
    {
        return this.m_sharedQueue.size();
    }
    
    /**
     * Adds the given object into the shared queue, so that the next
     * available thread will process it.
     */
    public void addObject( Object o )
    {
        checkThreshold();
        this.m_sharedQueue.enqueue( o );
    }
    
    /**
     * 
     */
    public int getThreadCount()
    {
        return this.m_numThreads;
    }
    
    /**
     * 
     */
    public int getMaximumThreadCount()
    {
        return this.m_maxThreads;
    }
    
    /**
     * 
     */
    public void setMaximumThreadCount( int max )
    {
        if (max < 1)
        {
            throw new IllegalArgumentException("maximum count "+max+
                " is out of bounds" );
        }
        this.m_maxThreads = max;
    }
    
    
    /**
     * Waits for all expecting objects in the queue to be processed,
     * and for each thread to finish processing an object.
     */
    public void waitForThreadsToFinish()
    {
        // wait for the SynchQueue to empty
        while (getObjectDepth() > 0)
        {
            Thread.yield();
        }
        
        Vector v = new Vector();
        synchronized (v)
        {
            // find all threads which are still processing objects
            for (int i = this.m_numThreads; --i >= 0;)
            {
                if (this.m_pool[i].isProcessingObjects())
                {
                    v.addElement( this.m_pool[i] );
                }
            }
            
            // wait for all threads to finish processing their objects
            QueueThread qt;
            while (v.size() > 0)
            {
                Thread.yield();
                for (int i = v.size(); --i >= 0;)
                {
                    qt = (QueueThread)v.elementAt(i);
                    if (!qt.isProcessingObjects())
                    {
                        v.removeElementAt(i);
                        // don't need to adjust i because
                        // we're procressing backwards.
                    }
                }
            }
        }
    }
    
    /**
     * Stops all threads.
     */
    public synchronized void stopThreads()
    {
        for (int i = this.m_numThreads; --i >= 0;)
        {
            if (this.m_pool[i] != null)
                this.m_pool[i].stop();
        }
    }
    
    /**
     * Suspends all threads.
     */
    public synchronized void suspendThreads()
    {
        for (int i = this.m_numThreads; --i >= 0;)
        {
            if (this.m_pool[i] != null)
                this.m_pool[i].suspend();
        }
    }
    
    /**
     * Resumes all threads.
     */
    public synchronized void resumeThreads()
    {
        for (int i = this.m_numThreads; --i >= 0;)
        {
            if (this.m_pool[i] != null)
                this.m_pool[i].resume();
        }
    }
    
    
    
    
    //----------------------------
    // Protected methods

    /**
     * If there are not enough threads, then add one into the
     * internal array, start the thread, and return the created
     * thread.
     *
     * @return the new thread, or <tt>null</tt> if the pool has
     *      exceeded its maximum thread count.
     */
    protected synchronized QueueThread addNewThread()
    {
        QueueThread qt = null;
        if (this.m_numThreads < this.m_maxThreads)
        {
            qt = this.m_pool[ this.m_numThreads++ ] =
                new QueueThread( createObjectListenerInstance(),
                this.m_sharedQueue );
            qt.start();
        }
        return qt;
    }
    
    
    /**
     * Checks if the depth on the shared queue is too deep (beyond the
     * threshold), and if so, creates a new thread to help deal with the
     * situation.
     */
    protected void checkThreshold()
    {
        if (this.m_sharedQueue.size() > this.m_depthThreshold)
        {
            addNewThread();
        }
    }
    
    /**
     * Create an instance of the basic object listener class, as given
     * in the constructor.
     *
     * @exception IllegalStateException thrown if there is an error
     *      creating a new instance of the class.
     */
    protected IObjectListener createObjectListenerInstance()
    {
        try
        {
//System.out.println("Creating an instance of class "+this.m_objListenerClass+
//", modifiers = "+(java.lang.reflect.Modifier.toString(
//this.m_objListenerClass.getModifiers())));
            IObjectListener ol = (IObjectListener)
                this.m_objListenerClass.newInstance();
            if (ol instanceof IThreadObjectListener)
            {
                ((IThreadObjectListener)ol).initialize(
                    this.m_objListenerInitData );
            }
            return ol;
        }
        catch (InstantiationException ie)
        {
            throw new IllegalStateException("could not instantiate from class "+
                this.m_objListenerClass.getName()+
                ": general instantiation exception "+ie.getMessage());
        }
        catch (IllegalAccessException iae)
        {
            throw new IllegalStateException("could not instantiate from class "+
                this.m_objListenerClass.getName()+
                ": could not access constructor "+iae.getMessage());
        }
        catch (ClassCastException cce)
        {
            throw new IllegalStateException("could not instantiate from class "+
                this.m_objListenerClass.getName()+": instance of wrong type "+
                cce.getMessage());
        }
    }
    
    //----------------------------
    // Private methods
}