summaryrefslogtreecommitdiff
path: root/java/src/IceInternal/ThreadPool.java
blob: 30cbf463e313e3751fd8c3c3c6a81cf1eaa4722d (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
// **********************************************************************
//
// Copyright (c) 2003-2011 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
    {
        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;
        }

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

        private final EventHandler _handler;
    }
    
    static final class JoinThreadWorkItem implements ThreadPoolWorkItem
    {
        public
        JoinThreadWorkItem(EventHandlerThread thread)
        {
            _thread = thread;
        }
        
        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).
            _thread.join();
        }
        
        private final EventHandlerThread _thread;
    }
 
    //
    // 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;
        _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(this, _instance, _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();
            joinWithAllThreads();
            throw ex;
        }
    }

    protected synchronized void
    finalize()
        throws Throwable
    {
        IceUtilInternal.Assert.FinalizerAssert(_destroyed);
    }

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

    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);
        _selector.update(handler, remove, add);
    }

    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
    execute(ThreadPoolWorkItem workItem)
    {
        _workQueue.queue(workItem);
    }

    public void
    joinWithAllThreads()
    {
        //
        // _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();
        }

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

    public String
    prefix()
    {
        return _prefix;
    }

    private void
    run(EventHandlerThread thread)
    {
        ThreadPoolCurrent current = new ThreadPoolCurrent(_instance, this);
        boolean select = false;
        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(_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)
                    {
                        _selector.finishSelect(_handlers, _serverIdleTime);
                        _nextHandler = _handlers.iterator();
                        select = false;
                    }
                    else if(!current._leader && followerWait(thread, 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.operation & SocketOperation.Read) != 0 && current._handler.hasMoreData())
                        {
                            _selector.hasMoreData(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.
                        //
                        _selector.enable(current._handler, current.operation);
                        assert(_inUse > 0);
                        --_inUse;
                    }

                    if(!current._leader && followerWait(thread, current))
                    {
                        return; // Wait timed-out.
                    }
                }
                else if(!current._ioCompleted && 
                        (current.operation & SocketOperation.Read) != 0 && current._handler.hasMoreData())
                {
                    _selector.hasMoreData(current._handler);
                }

                //
                // Get the next ready handler.
                //
                if(_nextHandler.hasNext())
                {
                    current._ioCompleted = false;
                    current._handler = _nextHandler.next();
                    current.operation = current._handler._ready;
                }
                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
                    {
                        _selector.startSelect();
                        select = true;
                    }
                }
                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);
                    }
                }
            }
        }
    }

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

        if(_sizeMax > 1)
        {
            synchronized(this)
            {
                --_inUseIO;
                
                if((current.operation & SocketOperation.Read) != 0 && current._handler.hasMoreData())
                {
                    _selector.hasMoreData(current._handler);
                }

                if(_serialize && !_destroyed)
                {
                    _selector.disable(current._handler, current.operation);
                }    
                
                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);
                        }
                    }
                }
            }
        }
        else if((current.operation & SocketOperation.Read) != 0 && current._handler.hasMoreData())
        {
            synchronized(this)
            {
                _selector.hasMoreData(current._handler);
            }
        }
    }
    
    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(EventHandlerThread thread, ThreadPoolCurrent current)
    {
        assert(!current._leader);

        //
        // 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)
        {
            try
            {
                if(_threadIdleTime > 0)
                {
                    long before = IceInternal.Time.currentMonotonicTimeMillis();
                    wait(_threadIdleTime * 1000);
                    if(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(thread);
                            _workQueue.queue(new JoinThreadWorkItem(thread));
                            return true;
                        }
                    }
                }
                else
                {
                    wait();
                }
            }
            catch(InterruptedException ex)
            {
            }
        }
        current._leader = true; // The current thread has become the leader.
        _promote = false;
        return false;
    }

    private final Instance _instance;
    private final ThreadPoolWorkQueue _workQueue;
    private boolean _destroyed;
    private final String _prefix;
    private final String _threadPrefix;
    private final Selector _selector;

    private final class EventHandlerThread implements Runnable
    {
        EventHandlerThread(String name)
        {
            _name = name;
        }

        public void
        join()
        {
            while(true)
            {
                try
                {
                    _thread.join();
                    break;
                }
                catch(InterruptedException ex)
                {
                }
            }
        }

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

        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(_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 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<EventHandler> _handlers = new java.util.ArrayList<EventHandler>();
    private java.util.Iterator<EventHandler> _nextHandler;

    private boolean _promote;
}