summaryrefslogtreecommitdiff
path: root/trunk/qpid/java/broker/src/main/java/org/apache/qpid/server/transport/ThreadPoolFilter.java
blob: bdd27f2d1c4f0375bed3296f55642069f3a206ae (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
/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
 */
package org.apache.qpid.server.transport;

import java.util.ArrayList;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.mina.common.IdleStatus;
import org.apache.mina.common.IoFilterAdapter;
import org.apache.mina.common.IoHandler;
import org.apache.mina.common.IoSession;
import org.apache.mina.util.BlockingQueue;
import org.apache.mina.util.ByteBufferUtil;
import org.apache.mina.util.IdentityHashSet;
import org.apache.mina.util.Queue;
import org.apache.mina.util.Stack;

/**
 * A Thread-pooling filter.  This filter forwards {@link IoHandler} events
 * to its thread pool.
 * <p/>
 * This is an implementation of
 * <a href="http://deuce.doc.wustl.edu/doc/pspdfs/lf.pdf">Leader/Followers
 * thread pool</a> by Douglas C. Schmidt et al.
 */
public class ThreadPoolFilter extends IoFilterAdapter
{
    /**
     * Default maximum size of thread pool (2G).
     */
    public static final int DEFAULT_MAXIMUM_POOL_SIZE = Integer.MAX_VALUE;

    /**
     * Default keep-alive time of thread pool (1 min).
     */
    public static final int DEFAULT_KEEP_ALIVE_TIME = 60 * 1000;

    /**
     * A queue which contains {@link Integer}s which represents reusable
     * thread IDs.  {@link Worker} first checks this queue and then
     * uses {@link #threadId} when no reusable thread ID is available.
     */
    private static final Queue threadIdReuseQueue = new Queue();
    private static int threadId = 0;

    private static int acquireThreadId()
    {
        synchronized (threadIdReuseQueue)
        {
            Integer id = (Integer) threadIdReuseQueue.pop();
            if (id == null)
            {
                return ++ threadId;
            }
            else
            {
                return id.intValue();
            }
        }
    }

    private static void releaseThreadId(int id)
    {
        synchronized (threadIdReuseQueue)
        {
            threadIdReuseQueue.push(new Integer(id));
        }
    }

    private final String threadNamePrefix;
    private final Map buffers = new IdentityHashMap();
    private final BlockingQueue unfetchedSessionBuffers = new BlockingQueue();
    private final Set allSessionBuffers = new IdentityHashSet();

    private Worker leader;
    private final Stack followers = new Stack();
    private final Set allWorkers = new IdentityHashSet();

    private int maximumPoolSize = DEFAULT_MAXIMUM_POOL_SIZE;
    private int keepAliveTime = DEFAULT_KEEP_ALIVE_TIME;

    private boolean shuttingDown;

    private int poolSize;
    private final Object poolSizeLock = new Object();

    /**
     * Creates a new instance of this filter with default thread pool settings.
     */
    public ThreadPoolFilter()
    {
        this("IoThreadPool");
    }

    /**
     * Creates a new instance of this filter with the specified thread name prefix
     * and other default settings.
     *
     * @param threadNamePrefix the prefix of the thread names this pool will create.
     */
    public ThreadPoolFilter(String threadNamePrefix)
    {
        if (threadNamePrefix == null)
        {
            throw new NullPointerException("threadNamePrefix");
        }
        threadNamePrefix = threadNamePrefix.trim();
        if (threadNamePrefix.length() == 0)
        {
            throw new IllegalArgumentException("threadNamePrefix is empty.");
        }
        this.threadNamePrefix = threadNamePrefix;
    }

    public String getThreadNamePrefix()
    {
        return threadNamePrefix;
    }

    public int getPoolSize()
    {
        synchronized (poolSizeLock)
        {
            return poolSize;
        }
    }

    public int getMaximumPoolSize()
    {
        return maximumPoolSize;
    }

    public int getKeepAliveTime()
    {
        return keepAliveTime;
    }

    public void setMaximumPoolSize(int maximumPoolSize)
    {
        if (maximumPoolSize <= 0)
        {
            throw new IllegalArgumentException();
        }
        this.maximumPoolSize = maximumPoolSize;
    }

    public void setKeepAliveTime(int keepAliveTime)
    {
        this.keepAliveTime = keepAliveTime;
    }

    public void init()
    {
        shuttingDown = false;
        leader = new Worker();
        leader.start();
        leader.lead();
    }

    public void destroy()
    {
        shuttingDown = true;
        int expectedPoolSize = 0;
        while (getPoolSize() != expectedPoolSize)
        {
            List allWorkers;
            synchronized (poolSizeLock)
            {
                allWorkers = new ArrayList(this.allWorkers);
            }

            // You may not interrupt the current thread.
            if (allWorkers.remove(Thread.currentThread()))
            {
                expectedPoolSize = 1;
            }

            for (Iterator i = allWorkers.iterator(); i.hasNext();)
            {
                Worker worker = (Worker) i.next();
                while (worker.isAlive())
                {
                    worker.interrupt();
                    try
                    {
                        // This timeout will help us from
                        // infinite lock-up and interrupt workers again.
                        worker.join(100);
                    }
                    catch (InterruptedException e)
                    {
                    }
                }
            }
        }

        this.allSessionBuffers.clear();
        this.unfetchedSessionBuffers.clear();
        this.buffers.clear();
        this.followers.clear();
        this.leader = null;
    }

    private void increasePoolSize(Worker worker)
    {
        synchronized (poolSizeLock)
        {
            poolSize++;
            allWorkers.add(worker);
        }
    }

    private void decreasePoolSize(Worker worker)
    {
        synchronized (poolSizeLock)
        {
            poolSize--;
            allWorkers.remove(worker);
        }
    }

    private void fireEvent(NextFilter nextFilter, IoSession session,
                           EventType type, Object data)
    {
        final BlockingQueue unfetchedSessionBuffers = this.unfetchedSessionBuffers;
        final Set allSessionBuffers = this.allSessionBuffers;
        final Event event = new Event(type, nextFilter, data);

        synchronized (unfetchedSessionBuffers)
        {
            final SessionBuffer buf = getSessionBuffer(session);
            final Queue eventQueue = buf.eventQueue;

            synchronized (buf)
            {
                eventQueue.push(event);
            }

            if (!allSessionBuffers.contains(buf))
            {
                allSessionBuffers.add(buf);
                unfetchedSessionBuffers.push(buf);
            }
        }
    }

    /**
     * Implement this method to fetch (or pop) a {@link SessionBuffer} from
     * the given <tt>unfetchedSessionBuffers</tt>.  The default implementation
     * simply pops the buffer from it.  You could prioritize the fetch order.
     *
     * @return A non-null {@link SessionBuffer}
     */
    protected SessionBuffer fetchSessionBuffer(Queue unfetchedSessionBuffers)
    {
        return (SessionBuffer) unfetchedSessionBuffers.pop();
    }

    private SessionBuffer getSessionBuffer(IoSession session)
    {
        final Map buffers = this.buffers;
        SessionBuffer buf = (SessionBuffer) buffers.get(session);
        if (buf == null)
        {
            synchronized (buffers)
            {
                buf = (SessionBuffer) buffers.get(session);
                if (buf == null)
                {
                    buf = new SessionBuffer(session);
                    buffers.put(session, buf);
                }
            }
        }
        return buf;
    }

    private void removeSessionBuffer(SessionBuffer buf)
    {
        final Map buffers = this.buffers;
        final IoSession session = buf.session;
        synchronized (buffers)
        {
            buffers.remove(session);
        }
    }

    protected static class SessionBuffer
    {
        private final IoSession session;

        private final Queue eventQueue = new Queue();

        private SessionBuffer(IoSession session)
        {
            this.session = session;
        }

        public IoSession getSession()
        {
            return session;
        }

        public Queue getEventQueue()
        {
            return eventQueue;
        }
    }

    private class Worker extends Thread
    {
        private final int id;
        private final Object promotionLock = new Object();
        private boolean dead;

        private Worker()
        {
            int id = acquireThreadId();
            this.id = id;
            this.setName(threadNamePrefix + '-' + id);
            increasePoolSize(this);
        }

        public boolean lead()
        {
            final Object promotionLock = this.promotionLock;
            synchronized (promotionLock)
            {
                if (dead)
                {
                    return false;
                }

                leader = this;
                promotionLock.notify();
            }

            return true;
        }

        public void run()
        {
            for (; ;)
            {
                if (!waitForPromotion())
                {
                    break;
                }

                SessionBuffer buf = fetchBuffer();
                giveUpLead();
                if (buf == null)
                {
                    break;
                }

                processEvents(buf);
                follow();
                releaseBuffer(buf);
            }

            decreasePoolSize(this);
            releaseThreadId(id);
        }

        private SessionBuffer fetchBuffer()
        {
            BlockingQueue unfetchedSessionBuffers = ThreadPoolFilter.this.unfetchedSessionBuffers;
            synchronized (unfetchedSessionBuffers)
            {
                while (!shuttingDown)
                {
                    try
                    {
                        unfetchedSessionBuffers.waitForNewItem();
                    }
                    catch (InterruptedException e)
                    {
                        continue;
                    }

                    return ThreadPoolFilter.this.fetchSessionBuffer(unfetchedSessionBuffers);
                }
            }

            return null;
        }

        private void processEvents(SessionBuffer buf)
        {
            final IoSession session = buf.session;
            final Queue eventQueue = buf.eventQueue;
            for (; ;)
            {
                Event event;
                synchronized (buf)
                {
                    event = (Event) eventQueue.pop();
                    if (event == null)
                    {
                        break;
                    }
                }
                processEvent(event.getNextFilter(), session,
                             event.getType(), event.getData());
            }
        }

        private void follow()
        {
            final Object promotionLock = this.promotionLock;
            final Stack followers = ThreadPoolFilter.this.followers;
            synchronized (promotionLock)
            {
                if (this != leader)
                {
                    synchronized (followers)
                    {
                        followers.push(this);
                    }
                }
            }
        }

        private void releaseBuffer(SessionBuffer buf)
        {
            final BlockingQueue unfetchedSessionBuffers = ThreadPoolFilter.this.unfetchedSessionBuffers;
            final Set allSessionBuffers = ThreadPoolFilter.this.allSessionBuffers;
            final Queue eventQueue = buf.eventQueue;

            synchronized (unfetchedSessionBuffers)
            {
                if (eventQueue.isEmpty())
                {
                    allSessionBuffers.remove(buf);
                    removeSessionBuffer(buf);
                }
                else
                {
                    unfetchedSessionBuffers.push(buf);
                }
            }
        }

        private boolean waitForPromotion()
        {
            final Object promotionLock = this.promotionLock;

            long startTime = System.currentTimeMillis();
            long currentTime = System.currentTimeMillis();

            synchronized (promotionLock)
            {
                while (this != leader && !shuttingDown)
                {
                    // Calculate remaining keep-alive time
                    int keepAliveTime = getKeepAliveTime();
                    if (keepAliveTime > 0)
                    {
                        keepAliveTime -= (currentTime - startTime);
                    }
                    else
                    {
                        keepAliveTime = Integer.MAX_VALUE;
                    }

                    // Break the loop if there's no remaining keep-alive time.
                    if (keepAliveTime <= 0)
                    {
                        break;
                    }

                    // Wait for promotion
                    try
                    {
                        promotionLock.wait(keepAliveTime);
                    }
                    catch (InterruptedException e)
                    {
                    }

                    // Update currentTime for the next iteration
                    currentTime = System.currentTimeMillis();
                }

                boolean timeToLead = this == leader && !shuttingDown;

                if (!timeToLead)
                {
                    // time to die
                    synchronized (followers)
                    {
                        followers.remove(this);
                    }

                    // Mark as dead explicitly when we've got promotionLock.
                    dead = true;
                }

                return timeToLead;
            }
        }

        private void giveUpLead()
        {
            final Stack followers = ThreadPoolFilter.this.followers;
            Worker worker;
            do
            {
                synchronized (followers)
                {
                    worker = (Worker) followers.pop();
                }

                if (worker == null)
                {
                    // Increase the number of threads if we
                    // are not shutting down and we can increase the number.
                    if (!shuttingDown
                            && getPoolSize() < getMaximumPoolSize())
                    {
                        worker = new Worker();
                        worker.lead();
                        worker.start();
                    }

                    // This loop should end because:
                    // 1) lead() is called already,
                    // 2) or it is shutting down and there's no more threads left.
                    break;
                }
            }
            while (!worker.lead());
        }
    }

    protected static class EventType
    {
        public static final EventType OPENED = new EventType("OPENED");

        public static final EventType CLOSED = new EventType("CLOSED");

        public static final EventType READ = new EventType("READ");

        public static final EventType WRITTEN = new EventType("WRITTEN");

        public static final EventType RECEIVED = new EventType("RECEIVED");

        public static final EventType SENT = new EventType("SENT");

        public static final EventType IDLE = new EventType("IDLE");

        public static final EventType EXCEPTION = new EventType("EXCEPTION");

        private final String value;

        private EventType(String value)
        {
            this.value = value;
        }

        public String toString()
        {
            return value;
        }
    }

    protected static class Event
    {
        private final EventType type;
        private final NextFilter nextFilter;
        private final Object data;

        public Event(EventType type, NextFilter nextFilter, Object data)
        {
            this.type = type;
            this.nextFilter = nextFilter;
            this.data = data;
        }

        public Object getData()
        {
            return data;
        }


        public NextFilter getNextFilter()
        {
            return nextFilter;
        }


        public EventType getType()
        {
            return type;
        }
    }

    public void sessionCreated(NextFilter nextFilter, IoSession session)
    {
        nextFilter.sessionCreated(session);
    }

    public void sessionOpened(NextFilter nextFilter,
                              IoSession session)
    {
        fireEvent(nextFilter, session, EventType.OPENED, null);
    }

    public void sessionClosed(NextFilter nextFilter,
                              IoSession session)
    {
        fireEvent(nextFilter, session, EventType.CLOSED, null);
    }

    public void sessionIdle(NextFilter nextFilter,
                            IoSession session, IdleStatus status)
    {
        fireEvent(nextFilter, session, EventType.IDLE, status);
    }

    public void exceptionCaught(NextFilter nextFilter,
                                IoSession session, Throwable cause)
    {
        fireEvent(nextFilter, session, EventType.EXCEPTION, cause);
    }

    public void messageReceived(NextFilter nextFilter,
                                IoSession session, Object message)
    {
        ByteBufferUtil.acquireIfPossible(message);
        fireEvent(nextFilter, session, EventType.RECEIVED, message);
    }

    public void messageSent(NextFilter nextFilter,
                            IoSession session, Object message)
    {
        ByteBufferUtil.acquireIfPossible(message);
        fireEvent(nextFilter, session, EventType.SENT, message);
    }

    protected void processEvent(NextFilter nextFilter,
                                IoSession session, EventType type,
                                Object data)
    {
        if (type == EventType.RECEIVED)
        {
            nextFilter.messageReceived(session, data);
            ByteBufferUtil.releaseIfPossible(data);
        }
        else if (type == EventType.SENT)
        {
            nextFilter.messageSent(session, data);
            ByteBufferUtil.releaseIfPossible(data);
        }
        else if (type == EventType.EXCEPTION)
        {
            nextFilter.exceptionCaught(session, (Throwable) data);
        }
        else if (type == EventType.IDLE)
        {
            nextFilter.sessionIdle(session, (IdleStatus) data);
        }
        else if (type == EventType.OPENED)
        {
            nextFilter.sessionOpened(session);
        }
        else if (type == EventType.CLOSED)
        {
            nextFilter.sessionClosed(session);
        }
    }

    public void filterWrite(NextFilter nextFilter, IoSession session, WriteRequest writeRequest)
    {
        nextFilter.filterWrite(session, writeRequest);
    }

    public void filterClose(NextFilter nextFilter, IoSession session) throws Exception
    {
        nextFilter.filterClose(session);
    }
}