summaryrefslogtreecommitdiff
path: root/java/src/IceInternal/ThreadPool.java
blob: 0e57a6a61c77f6d56393ca62b19bda808696267c (plain)
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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
// **********************************************************************
//
// Copyright (c) 2003-2014 ZeroC, Inc. All rights reserved.
//
// This copy of Ice is licensed to you under the terms described in the
// ICE_LICENSE file included in this distribution.
//
// **********************************************************************

package IceInternal;

public final class ThreadPool
{
    final class ShutdownWorkItem implements ThreadPoolWorkItem
    {
        @Override
        public void execute(ThreadPoolCurrent current)
        {
            current.ioCompleted();
            try
            {
                _instance.objectAdapterFactory().shutdown();
            }
            catch(Ice.CommunicatorDestroyedException ex)
            {
            }
        }
    }

    static final class FinishedWorkItem implements ThreadPoolWorkItem
    {
        public
        FinishedWorkItem(EventHandler handler)
        {
            _handler = handler;
        }

        @Override
        public void execute(ThreadPoolCurrent current)
        {
            _handler.finished(current);
        }

        private final EventHandler _handler;
    }

    static final class JoinThreadWorkItem implements ThreadPoolWorkItem
    {
        public
        JoinThreadWorkItem(EventHandlerThread thread)
        {
            _thread = thread;
        }

        @Override
        public void execute(ThreadPoolCurrent current)
        {
            // No call to ioCompleted, this shouldn't block (and we don't want to cause
            // a new thread to be started).
            try
            {
                _thread.join();
            }
            catch (InterruptedException e)
            {
                // Ignore.
            }
        }

        private final EventHandlerThread _thread;
    }

    static final class InterruptWorkItem implements ThreadPoolWorkItem
    {
        @Override
        public void execute(ThreadPoolCurrent current)
        {
            // Nothing to do, this is just used to interrupt the thread pool selector.
        }
    }

    private static ThreadPoolWorkItem _interruptWorkItem = new InterruptWorkItem();

    //
    // Exception raised by the thread pool work queue when the thread pool
    // is destroyed.
    //
    static final class DestroyedException extends RuntimeException
    {
    }

    public
    ThreadPool(Instance instance, String prefix, int timeout)
    {
        _instance = instance;
        _dispatcher = instance.initializationData().dispatcher;
        _destroyed = false;
        _prefix = prefix;
        _selector = new Selector(instance);
        _threadIndex = 0;
        _inUse = 0;
        _inUseIO = 0;
        _promote = true;
        _serialize = _instance.initializationData().properties.getPropertyAsInt(_prefix + ".Serialize") > 0;
        _serverIdleTime = timeout;

        Ice.Properties properties = _instance.initializationData().properties;

        String programName = properties.getProperty("Ice.ProgramName");
        if(programName.length() > 0)
        {
            _threadPrefix = programName + "-" + _prefix;
        }
        else
        {
            _threadPrefix = _prefix;
        }

        int nProcessors = Runtime.getRuntime().availableProcessors();

        //
        // We use just one thread as the default. This is the fastest
        // possible setting, still allows one level of nesting, and
        // doesn't require to make the servants thread safe.
        //
        int size = properties.getPropertyAsIntWithDefault(_prefix + ".Size", 1);
        if(size < 1)
        {
            String s = _prefix + ".Size < 1; Size adjusted to 1";
            _instance.initializationData().logger.warning(s);
            size = 1;
        }

        int sizeMax = properties.getPropertyAsIntWithDefault(_prefix + ".SizeMax", size);
        if(sizeMax == -1)
        {
            sizeMax = nProcessors;
        }
        if(sizeMax < size)
        {
            String s = _prefix + ".SizeMax < " + _prefix + ".Size; SizeMax adjusted to Size (" + size + ")";
            _instance.initializationData().logger.warning(s);
            sizeMax = size;
        }

        int sizeWarn = properties.getPropertyAsInt(_prefix + ".SizeWarn");
        if(sizeWarn != 0 && sizeWarn < size)
        {
            String s = _prefix + ".SizeWarn < " + _prefix + ".Size; adjusted SizeWarn to Size (" + size + ")";
            _instance.initializationData().logger.warning(s);
            sizeWarn = size;
        }
        else if(sizeWarn > sizeMax)
        {
            String s = _prefix + ".SizeWarn > " + _prefix + ".SizeMax; adjusted SizeWarn to SizeMax (" + sizeMax + ")";
            _instance.initializationData().logger.warning(s);
            sizeWarn = sizeMax;
        }

        int threadIdleTime = properties.getPropertyAsIntWithDefault(_prefix + ".ThreadIdleTime", 60);
        if(threadIdleTime < 0)
        {
            String s = _prefix + ".ThreadIdleTime < 0; ThreadIdleTime adjusted to 0";
            _instance.initializationData().logger.warning(s);
            threadIdleTime = 0;
        }

        _size = size;
        _sizeMax = sizeMax;
        _sizeWarn = sizeWarn;
        _sizeIO = Math.min(sizeMax, nProcessors);
        _threadIdleTime = threadIdleTime;

        int stackSize = properties.getPropertyAsInt( _prefix + ".StackSize");
        if(stackSize < 0)
        {
            String s = _prefix + ".StackSize < 0; Size adjusted to JRE default";
            _instance.initializationData().logger.warning(s);
            stackSize = 0;
        }
        _stackSize = stackSize;

        boolean hasPriority = properties.getProperty(_prefix + ".ThreadPriority").length() > 0;
        int priority = properties.getPropertyAsInt(_prefix + ".ThreadPriority");
        if(!hasPriority)
        {
            hasPriority = properties.getProperty("Ice.ThreadPriority").length() > 0;
            priority = properties.getPropertyAsInt("Ice.ThreadPriority");
        }
        _hasPriority = hasPriority;
        _priority = priority;

        _workQueue = new ThreadPoolWorkQueue(_instance, this, _selector);

        _nextHandler = _handlers.iterator();

        if(_instance.traceLevels().threadPool >= 1)
        {
            String s = "creating " + _prefix + ": Size = " + _size + ", SizeMax = " + _sizeMax + ", SizeWarn = " +
                       _sizeWarn;
            _instance.initializationData().logger.trace(_instance.traceLevels().threadPoolCat, s);
        }

        try
        {
            for(int i = 0; i < _size; i++)
            {
                EventHandlerThread thread = new EventHandlerThread(_threadPrefix + "-" + _threadIndex++);
                _threads.add(thread);
                if(_hasPriority)
                {
                    thread.start(_priority);
                }
                else
                {
                    thread.start(java.lang.Thread.NORM_PRIORITY);
                }
            }
        }
        catch(RuntimeException ex)
        {
            String s = "cannot create thread for `" + _prefix + "':\n" + Ex.toString(ex);
            _instance.initializationData().logger.error(s);

            destroy();
            try
            {
                joinWithAllThreads();
            }
            catch (InterruptedException e)
            {
                throw new Ice.OperationInterruptedException();
            }
            throw ex;
        }
    }

    @Override
    protected synchronized void
    finalize()
        throws Throwable
    {
        try
        {
            IceUtilInternal.Assert.FinalizerAssert(_destroyed);
        }
        catch(java.lang.Exception ex)
        {
        }
        finally
        {
            super.finalize();
        }
    }

    public synchronized void
    destroy()
    {
        assert(!_destroyed);
        _destroyed = true;
        _workQueue.destroy();
    }

    public synchronized void
    updateObservers()
    {
        for(EventHandlerThread thread : _threads)
        {
            thread.updateObserver();
        }
    }

    public synchronized void
    initialize(EventHandler handler)
    {
        assert(!_destroyed);
        _selector.initialize(handler);
    }

    public void
    register(EventHandler handler, int op)
    {
        update(handler, SocketOperation.None, op);
    }

    public synchronized void
    update(EventHandler handler, int remove, int add)
    {
        assert(!_destroyed);

        // Don't remove what needs to be added
        remove &= ~add;

        // Don't remove/add if already un-registered or registered
        remove = handler._registered & remove;
        add = ~handler._registered & add;
        if(remove == add)
        {
            return;
        }
        _selector.update(handler, remove, add);

        if((add & SocketOperation.Read) != 0 && handler._hasMoreData.value &&
           (handler._disabled & SocketOperation.Read) == 0)
        {
            if(_pendingHandlers.isEmpty())
            {
                _workQueue.queue(_interruptWorkItem); // Interrupt select()
            }
            _pendingHandlers.add(handler);
        }
        else if((remove & SocketOperation.Read) != 0)
        {
            _pendingHandlers.remove(handler);
        }
    }

    public void
    unregister(EventHandler handler, int op)
    {
        update(handler, op, SocketOperation.None);
    }

    public synchronized void
    finish(EventHandler handler)
    {
        assert(!_destroyed);
        _selector.finish(handler);
        _workQueue.queue(new FinishedWorkItem(handler));
    }

    public void
    dispatchFromThisThread(DispatchWorkItem workItem)
    {
        if(_dispatcher != null)
        {
            try
            {
                _dispatcher.dispatch(workItem, workItem.getConnection());
            }
            catch(java.lang.Exception ex)
            {
                if(_instance.initializationData().properties.getPropertyAsIntWithDefault("Ice.Warn.Dispatch", 1) > 1)
                {
                    java.io.StringWriter sw = new java.io.StringWriter();
                    java.io.PrintWriter pw = new java.io.PrintWriter(sw);
                    ex.printStackTrace(pw);
                    pw.flush();
                    _instance.initializationData().logger.warning("dispatch exception:\n" + sw.toString());
                }
            }
        }
        else
        {
            workItem.run();
        }
    }

    public void
    dispatch(DispatchWorkItem workItem)
    {
        _workQueue.queue(workItem);
    }

    public void
    joinWithAllThreads()
        throws InterruptedException
    {
        //
        // _threads is immutable after destroy() has been called,
        // therefore no synchronization is needed. (Synchronization
        // wouldn't be possible here anyway, because otherwise the
        // other threads would never terminate.)
        //
        for(EventHandlerThread thread : _threads)
        {
            thread.join();
        }

        //
        // TODO: MJN: InterruptedException leads to a leak as the
        // work queue and selector are not destroyed?
        //

        //
        // Destroy the selector
        //
        _workQueue.close();
        _selector.destroy();
    }

    public String
    prefix()
    {
        return _prefix;
    }

    private void
    run(EventHandlerThread thread)
    {
        ThreadPoolCurrent current = new ThreadPoolCurrent(_instance, this, thread);
        boolean select = false;
        java.util.List<EventHandlerOpPair> handlers = new java.util.ArrayList<EventHandlerOpPair>();

        while(true)
        {
            if(current._handler != null)
            {
                try
                {
                    current._handler.message(current);
                }
                catch(DestroyedException ex)
                {
                    return;
                }
                catch(java.lang.Exception ex)
                {
                    String s = "exception in `" + _prefix + "':\n" + Ex.toString(ex);
                    s += "\nevent handler: " + current._handler.toString();
                    _instance.initializationData().logger.error(s);
                }
            }
            else if(select)
            {
                try
                {
                    _selector.select(handlers, _serverIdleTime);
                }
                catch(Selector.TimeoutException ex)
                {
                    synchronized(this)
                    {
                        if(!_destroyed && _inUse == 0)
                        {
                            _workQueue.queue(new ShutdownWorkItem()); // Select timed-out.
                        }
                        continue;
                    }
                }
            }

            synchronized(this)
            {
                if(current._handler == null)
                {
                    if(select)
                    {
                        java.util.List<EventHandlerOpPair> tmp = _handlers;
                        _handlers = handlers;
                        handlers = tmp;

                        if(!_pendingHandlers.isEmpty())
                        {
                            for(EventHandlerOpPair pair : _handlers)
                            {
                                _pendingHandlers.remove(pair.handler);
                            }
                            for(EventHandler p : _pendingHandlers)
                            {
                                _handlers.add(new EventHandlerOpPair(p, SocketOperation.Read));
                            }
                            _pendingHandlers.clear();
                        }

                        _nextHandler = _handlers.iterator();
                        _selector.finishSelect();
                        select = false;
                    }
                    else if(!current._leader && followerWait(current))
                    {
                        return; // Wait timed-out.
                    }
                }
                else if(_sizeMax > 1)
                {
                    if(!current._ioCompleted)
                    {
                        //
                        // The handler didn't call ioCompleted() so we take care of decreasing
                        // the IO thread count now.
                        //
                        --_inUseIO;

                        if(current._handler._hasMoreData.value &&
                           (current._handler._registered & SocketOperation.Read) != 0)
                        {
                            if(_pendingHandlers.isEmpty())
                            {
                                _workQueue.queue(_interruptWorkItem);
                            }
                            _pendingHandlers.add(current._handler);
                        }
                    }
                    else
                    {
                        //
                        // If the handler called ioCompleted(), we re-enable the handler in
                        // case it was disabled and we decrease the number of thread in use.
                        //
                        if(_serialize)
                        {
                            _selector.enable(current._handler, current.operation);
                            if(current._handler._hasMoreData.value &&
                               (current._handler._registered & SocketOperation.Read) != 0)
                            {
                                if(_pendingHandlers.isEmpty())
                                {
                                    _workQueue.queue(_interruptWorkItem); // Interrupt select()
                                }
                                _pendingHandlers.add(current._handler);
                            }
                        }
                        assert(_inUse > 0);
                        --_inUse;
                    }

                    if(!current._leader && followerWait(current))
                    {
                        return; // Wait timed-out.
                    }
                }
                else if(current._handler._hasMoreData.value &&
                        (current._handler._registered & SocketOperation.Read) != 0)
                {
                    if(_pendingHandlers.isEmpty())
                    {
                        _workQueue.queue(_interruptWorkItem); // Interrupt select()
                    }
                    _pendingHandlers.add(current._handler);
                }

                //
                // Get the next ready handler.
                //
                EventHandlerOpPair next = null;
                while(_nextHandler.hasNext())
                {
                    EventHandlerOpPair n = _nextHandler.next();
                    if((n.op & n.handler._registered) != 0)
                    {
                        next = n;
                        break;
                    }
                }
                if(next != null)
                {
                    current._ioCompleted = false;
                    current._handler = next.handler;
                    current.operation = next.op;
                    thread.setState(Ice.Instrumentation.ThreadState.ThreadStateInUseForIO);
                }
                else
                {
                    current._handler = null;
                }

                if(current._handler == null)
                {
                    //
                    // If there are no more ready handlers and there are still threads busy performing
                    // IO, we give up leadership and promote another follower (which will perform the
                    // select() only once all the IOs are completed). Otherwise, if there's no more
                    // threads peforming IOs, it's time to do another select().
                    //
                    if(_inUseIO > 0)
                    {
                        promoteFollower(current);
                    }
                    else
                    {
                        _handlers.clear();
                        _selector.startSelect();
                        select = true;
                        thread.setState(Ice.Instrumentation.ThreadState.ThreadStateIdle);
                    }
                }
                else if(_sizeMax > 1)
                {
                    //
                    // Increment the IO thread count and if there's still threads available
                    // to perform IO and more handlers ready, we promote a follower.
                    //
                    ++_inUseIO;
                    if(_nextHandler.hasNext() && _inUseIO < _sizeIO)
                    {
                        promoteFollower(current);
                    }
                }
            }
        }
    }

    synchronized void
    ioCompleted(ThreadPoolCurrent current)
    {
        current._ioCompleted = true; // Set the IO completed flag to specify that ioCompleted() has been called.

        current._thread.setState(Ice.Instrumentation.ThreadState.ThreadStateInUseForUser);

        if(_sizeMax > 1)
        {
            --_inUseIO;

            if(!_destroyed)
            {
                if(_serialize)
                {
                    _selector.disable(current._handler, current.operation);

                    // Make sure the handler isn't in the set of pending handlers (this can
                    // for example occur if the handler is has more data and its added by
                    // ThreadPool::update while we were processing IO).
                    _pendingHandlers.remove(current._handler);
                }
                else if(current._handler._hasMoreData.value &&
                        (current._handler._registered & SocketOperation.Read) != 0)
                {
                    if(_pendingHandlers.isEmpty())
                    {
                        _workQueue.queue(_interruptWorkItem); // Interrupt select()
                    }
                    _pendingHandlers.add(current._handler);
                }
            }

            if(current._leader)
            {
                //
                // If this thread is still the leader, it's time to promote a new leader.
                //
                promoteFollower(current);
            }
            else if(_promote && (_nextHandler.hasNext() || _inUseIO == 0))
            {
                notify();
            }

            assert(_inUse >= 0);
            ++_inUse;

            if(_inUse == _sizeWarn)
            {
                String s = "thread pool `" + _prefix + "' is running low on threads\n"
                    + "Size=" + _size + ", " + "SizeMax=" + _sizeMax + ", " + "SizeWarn=" + _sizeWarn;
                _instance.initializationData().logger.warning(s);
            }

            if(!_destroyed)
            {
                assert(_inUse <= _threads.size());
                if(_inUse < _sizeMax && _inUse == _threads.size())
                {
                    if(_instance.traceLevels().threadPool >= 1)
                    {
                        String s = "growing " + _prefix + ": Size=" + (_threads.size() + 1);
                        _instance.initializationData().logger.trace(_instance.traceLevels().threadPoolCat, s);
                    }

                    try
                    {
                        EventHandlerThread thread = new EventHandlerThread(_threadPrefix + "-" + _threadIndex++);
                        _threads.add(thread);
                        if(_hasPriority)
                        {
                            thread.start(_priority);
                        }
                        else
                        {
                            thread.start(java.lang.Thread.NORM_PRIORITY);
                        }
                    }
                    catch(RuntimeException ex)
                    {
                        String s = "cannot create thread for `" + _prefix + "':\n" + Ex.toString(ex);
                        _instance.initializationData().logger.error(s);
                    }
                }
            }
        }
    }

    private synchronized void
    promoteFollower(ThreadPoolCurrent current)
    {
        assert(!_promote && current._leader);
        _promote = true;
        if(_inUseIO < _sizeIO && (_nextHandler.hasNext() || _inUseIO == 0))
        {
            notify();
        }
        current._leader = false;
    }

    private synchronized boolean
    followerWait(ThreadPoolCurrent current)
    {
        assert(!current._leader);

        current._thread.setState(Ice.Instrumentation.ThreadState.ThreadStateIdle);

        //
        // It's important to clear the handler before waiting to make sure that
        // resources for the handler are released now if it's finished. We also
        // clear the per-thread stream.
        //
        current._handler = null;
        current.stream.reset();

        //
        // Wait to be promoted and for all the IO threads to be done.
        //
        while(!_promote || _inUseIO == _sizeIO || (!_nextHandler.hasNext() && _inUseIO > 0))
        {
            if(_threadIdleTime > 0)
            {
                long before = IceInternal.Time.currentMonotonicTimeMillis();
                boolean interrupted = false;
                try
                {
                    //
                    // If the wait is interrupted then we'll let the thread die as if it timed out.
                    //
                    wait(_threadIdleTime * 1000);
                }
                catch (InterruptedException e)
                {
                    interrupted = true;
                }
                if(interrupted || IceInternal.Time.currentMonotonicTimeMillis() - before >= _threadIdleTime * 1000)
                {
                    if(!_destroyed && (!_promote || _inUseIO == _sizeIO ||
                                       (!_nextHandler.hasNext() && _inUseIO > 0)))
                    {
                        if(_instance.traceLevels().threadPool >= 1)
                        {
                            String s = "shrinking " + _prefix + ": Size=" + (_threads.size() - 1);
                            _instance.initializationData().logger.trace(_instance.traceLevels().threadPoolCat, s);
                        }
                        assert(_threads.size() > 1); // Can only be called by a waiting follower thread.
                        _threads.remove(current._thread);
                        _workQueue.queue(new JoinThreadWorkItem(current._thread));
                        return true;
                    }
                }
            }
            else
            {
                try
                {
                    wait();
                }
                catch (InterruptedException e)
                {
                    //
                    // Eat the InterruptedException.
                    //
                }
            }
        }
        current._leader = true; // The current thread has become the leader.
        _promote = false;
        return false;
    }

    private final Instance _instance;
    private final Ice.Dispatcher _dispatcher;
    private final ThreadPoolWorkQueue _workQueue;
    private boolean _destroyed;
    private final String _prefix;
    private final String _threadPrefix;
    private final Selector _selector;

    final class EventHandlerThread implements Runnable
    {
        EventHandlerThread(String name)
        {
            _name = name;
            _state = Ice.Instrumentation.ThreadState.ThreadStateIdle;
            updateObserver();
        }

        public void
        updateObserver()
        {
            // Must be called with the thread pool mutex locked
            Ice.Instrumentation.CommunicatorObserver obsv = _instance.getObserver();
            if(obsv != null)
            {
                _observer = obsv.getThreadObserver(_prefix, _name, _state, _observer);
                if(_observer != null)
                {
                    _observer.attach();
                }
            }
        }

        public void
        setState(Ice.Instrumentation.ThreadState s)
        {
            // Must be called with the thread pool mutex locked
            if(_observer != null)
            {
                if(_state != s)
                {
                    _observer.stateChanged(_state, s);
                }
            }
            _state = s;
        }

        public void
        join()
            throws InterruptedException
        {
            _thread.join();
        }

        public void
        start(int priority)
        {
            _thread = new Thread(null, this, _name, _stackSize);
            _thread.setPriority(priority);
            _thread.start();
        }

        @Override
        public void
        run()
        {
            if(_instance.initializationData().threadHook != null)
            {
                try
                {
                    _instance.initializationData().threadHook.start();
                }
                catch(java.lang.Exception ex)
                {
                    String s = "thread hook start() method raised an unexpected exception in `";
                    s += _prefix + "' thread " + _name + ":\n" + Ex.toString(ex);
                    _instance.initializationData().logger.error(s);
                }
            }

            try
            {
                ThreadPool.this.run(this);
            }
            catch(java.lang.Exception ex)
            {
                String s = "exception in `" + _prefix + "' thread " + _name + ":\n" + Ex.toString(ex);
                _instance.initializationData().logger.error(s);
            }

            if(_observer != null)
            {
                _observer.detach();
            }

            if(_instance.initializationData().threadHook != null)
            {
                try
                {
                    _instance.initializationData().threadHook.stop();
                }
                catch(java.lang.Exception ex)
                {
                    String s = "thread hook stop() method raised an unexpected exception in `";
                    s += _prefix + "' thread " + _name + ":\n" + Ex.toString(ex);
                    _instance.initializationData().logger.error(s);
                }
            }
        }

        final private String _name;
        private Thread _thread;
        private Ice.Instrumentation.ThreadState _state;
        private Ice.Instrumentation.ThreadObserver _observer;
    }

    private final int _size; // Number of threads that are pre-created.
    private final int _sizeIO; // Number of threads that can concurrently perform IO.
    private final int _sizeMax; // Maximum number of threads.
    private final int _sizeWarn; // If _inUse reaches _sizeWarn, a "low on threads" warning will be printed.
    private final boolean _serialize; // True if requests need to be serialized over the connection.
    private final int _priority;
    private final boolean _hasPriority;
    private final long _serverIdleTime;
    private final long _threadIdleTime;
    private final int _stackSize;

    private java.util.List<EventHandlerThread> _threads = new java.util.ArrayList<EventHandlerThread>();
    private int _threadIndex; // For assigning thread names.
    private int _inUse; // Number of threads that are currently in use.
    private int _inUseIO; // Number of threads that are currently performing IO.

    private java.util.List<EventHandlerOpPair> _handlers = new java.util.ArrayList<EventHandlerOpPair>();
    private java.util.Iterator<EventHandlerOpPair> _nextHandler;
    private java.util.HashSet<EventHandler> _pendingHandlers = new java.util.HashSet<EventHandler>();

    private boolean _promote;
}