View Javadoc
1   /*
2    * Copyright 2014 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    * https://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  package io.netty.handler.traffic;
17  
18  import static io.netty.util.internal.ObjectUtil.checkNotNullWithIAE;
19  import static io.netty.util.internal.ObjectUtil.checkPositive;
20  import static io.netty.util.internal.ObjectUtil.checkPositiveOrZero;
21  
22  import io.netty.channel.Channel;
23  import io.netty.channel.ChannelId;
24  import io.netty.channel.ChannelHandler.Sharable;
25  import io.netty.channel.ChannelConfig;
26  import io.netty.channel.ChannelHandlerContext;
27  import io.netty.channel.ChannelPromise;
28  import io.netty.util.Attribute;
29  import io.netty.util.concurrent.EventExecutor;
30  import io.netty.util.internal.logging.InternalLogger;
31  import io.netty.util.internal.logging.InternalLoggerFactory;
32  
33  import java.nio.channels.ClosedChannelException;
34  import java.util.AbstractCollection;
35  import java.util.ArrayDeque;
36  import java.util.Collection;
37  import java.util.Iterator;
38  import java.util.concurrent.ConcurrentHashMap;
39  import java.util.concurrent.ConcurrentMap;
40  import java.util.concurrent.ScheduledExecutorService;
41  import java.util.concurrent.TimeUnit;
42  import java.util.concurrent.atomic.AtomicLong;
43  
44  /**
45   * This implementation of the {@link AbstractTrafficShapingHandler} is for global
46   * and per channel traffic shaping, that is to say a global limitation of the bandwidth, whatever
47   * the number of opened channels and a per channel limitation of the bandwidth.<br><br>
48   * This version shall not be in the same pipeline than other TrafficShapingHandler.<br><br>
49   *
50   * The general use should be as follow:<br>
51   * <ul>
52   * <li>Create your unique GlobalChannelTrafficShapingHandler like:<br><br>
53   * <tt>GlobalChannelTrafficShapingHandler myHandler = new GlobalChannelTrafficShapingHandler(executor);</tt><br><br>
54   * The executor could be the underlying IO worker pool<br>
55   * <tt>pipeline.addLast(myHandler);</tt><br><br>
56   *
57   * <b>Note that this handler has a Pipeline Coverage of "all" which means only one such handler must be created
58   * and shared among all channels as the counter must be shared among all channels.</b><br><br>
59   *
60   * Other arguments can be passed like write or read limitation (in bytes/s where 0 means no limitation)
61   * or the check interval (in millisecond) that represents the delay between two computations of the
62   * bandwidth and so the call back of the doAccounting method (0 means no accounting at all).<br>
63   * Note that as this is a fusion of both Global and Channel Traffic Shaping, limits are in 2 sets,
64   * respectively Global and Channel.<br><br>
65   *
66   * A value of 0 means no accounting for checkInterval. If you need traffic shaping but no such accounting,
67   * it is recommended to set a positive value, even if it is high since the precision of the
68   * Traffic Shaping depends on the period where the traffic is computed. The highest the interval,
69   * the less precise the traffic shaping will be. It is suggested as higher value something close
70   * to 5 or 10 minutes.<br><br>
71   *
72   * maxTimeToWait, by default set to 15s, allows to specify an upper bound of time shaping.<br><br>
73   * </li>
74   * <li>In your handler, you should consider to use the {@code channel.isWritable()} and
75   * {@code channelWritabilityChanged(ctx)} to handle writability, or through
76   * {@code future.addListener(new GenericFutureListener())} on the future returned by
77   * {@code ctx.write()}.</li>
78   * <li>You shall also consider to have object size in read or write operations relatively adapted to
79   * the bandwidth you required: for instance having 10 MB objects for 10KB/s will lead to burst effect,
80   * while having 100 KB objects for 1 MB/s should be smoothly handle by this TrafficShaping handler.<br><br></li>
81   * <li>Some configuration methods will be taken as best effort, meaning
82   * that all already scheduled traffics will not be
83   * changed, but only applied to new traffics.<br>
84   * So the expected usage of those methods are to be used not too often,
85   * accordingly to the traffic shaping configuration.</li>
86   * </ul><br>
87   *
88   * Be sure to call {@link #release()} once this handler is not needed anymore to release all internal resources.
89   * This will not shutdown the {@link EventExecutor} as it may be shared, so you need to do this by your own.
90   */
91  @Sharable
92  public class GlobalChannelTrafficShapingHandler extends AbstractTrafficShapingHandler {
93      private static final InternalLogger logger =
94              InternalLoggerFactory.getInstance(GlobalChannelTrafficShapingHandler.class);
95      /**
96       * All queues per channel
97       */
98      final ConcurrentMap<ChannelId, PerChannel> channelQueues = new ConcurrentHashMap<>();
99  
100     /**
101      * Global queues size
102      */
103     private final AtomicLong queuesSize = new AtomicLong();
104 
105     /**
106      * Maximum cumulative writing bytes for one channel among all (as long as channels stay the same)
107      */
108     private final AtomicLong cumulativeWrittenBytes = new AtomicLong();
109 
110     /**
111      * Maximum cumulative read bytes for one channel among all (as long as channels stay the same)
112      */
113     private final AtomicLong cumulativeReadBytes = new AtomicLong();
114 
115     /**
116      * Max size in the list before proposing to stop writing new objects from next handlers
117      * for all channel (global)
118      */
119     volatile long maxGlobalWriteSize = DEFAULT_MAX_SIZE * 100; // default 400MB
120 
121     /**
122      * Limit in B/s to apply to write
123      */
124     private volatile long writeChannelLimit;
125 
126     /**
127      * Limit in B/s to apply to read
128      */
129     private volatile long readChannelLimit;
130 
131     private static final float DEFAULT_DEVIATION = 0.1F;
132     private static final float MAX_DEVIATION = 0.4F;
133     private static final float DEFAULT_SLOWDOWN = 0.4F;
134     private static final float DEFAULT_ACCELERATION = -0.1F;
135     private volatile float maxDeviation;
136     private volatile float accelerationFactor;
137     private volatile float slowDownFactor;
138     private volatile boolean readDeviationActive;
139     private volatile boolean writeDeviationActive;
140 
141     static final class PerChannel {
142         ArrayDeque<ToSend> messagesQueue;
143         TrafficCounter channelTrafficCounter;
144         long queueSize;
145         long lastWriteTimestamp;
146         long lastReadTimestamp;
147     }
148 
149     /**
150      * Create the global TrafficCounter
151      */
152     void createGlobalTrafficCounter(ScheduledExecutorService executor) {
153         // Default
154         setMaxDeviation(DEFAULT_DEVIATION, DEFAULT_SLOWDOWN, DEFAULT_ACCELERATION);
155         checkNotNullWithIAE(executor, "executor");
156         TrafficCounter tc = new GlobalChannelTrafficCounter(this, executor, "GlobalChannelTC", checkInterval);
157         setTrafficCounter(tc);
158         tc.start();
159     }
160 
161     @Override
162     protected int userDefinedWritabilityIndex() {
163         return AbstractTrafficShapingHandler.GLOBALCHANNEL_DEFAULT_USER_DEFINED_WRITABILITY_INDEX;
164     }
165 
166     /**
167      * Create a new instance.
168      *
169      * @param executor
170      *            the {@link ScheduledExecutorService} to use for the {@link TrafficCounter}.
171      * @param writeGlobalLimit
172      *            0 or a limit in bytes/s
173      * @param readGlobalLimit
174      *            0 or a limit in bytes/s
175      * @param writeChannelLimit
176      *            0 or a limit in bytes/s
177      * @param readChannelLimit
178      *            0 or a limit in bytes/s
179      * @param checkInterval
180      *            The delay between two computations of performances for
181      *            channels or 0 if no stats are to be computed.
182      * @param maxTime
183      *            The maximum delay to wait in case of traffic excess.
184      */
185     public GlobalChannelTrafficShapingHandler(ScheduledExecutorService executor,
186             long writeGlobalLimit, long readGlobalLimit,
187             long writeChannelLimit, long readChannelLimit,
188             long checkInterval, long maxTime) {
189         super(writeGlobalLimit, readGlobalLimit, checkInterval, maxTime);
190         createGlobalTrafficCounter(executor);
191         this.writeChannelLimit = writeChannelLimit;
192         this.readChannelLimit = readChannelLimit;
193     }
194 
195     /**
196      * Create a new instance.
197      *
198      * @param executor
199      *          the {@link ScheduledExecutorService} to use for the {@link TrafficCounter}.
200      * @param writeGlobalLimit
201      *            0 or a limit in bytes/s
202      * @param readGlobalLimit
203      *            0 or a limit in bytes/s
204      * @param writeChannelLimit
205      *            0 or a limit in bytes/s
206      * @param readChannelLimit
207      *            0 or a limit in bytes/s
208      * @param checkInterval
209      *          The delay between two computations of performances for
210      *            channels or 0 if no stats are to be computed.
211      */
212     public GlobalChannelTrafficShapingHandler(ScheduledExecutorService executor,
213             long writeGlobalLimit, long readGlobalLimit,
214             long writeChannelLimit, long readChannelLimit,
215             long checkInterval) {
216         super(writeGlobalLimit, readGlobalLimit, checkInterval);
217         this.writeChannelLimit = writeChannelLimit;
218         this.readChannelLimit = readChannelLimit;
219         createGlobalTrafficCounter(executor);
220     }
221 
222     /**
223      * Create a new instance.
224      *
225      * @param executor
226      *          the {@link ScheduledExecutorService} to use for the {@link TrafficCounter}.
227      * @param writeGlobalLimit
228      *            0 or a limit in bytes/s
229      * @param readGlobalLimit
230      *            0 or a limit in bytes/s
231      * @param writeChannelLimit
232      *            0 or a limit in bytes/s
233      * @param readChannelLimit
234      *            0 or a limit in bytes/s
235      */
236     public GlobalChannelTrafficShapingHandler(ScheduledExecutorService executor,
237             long writeGlobalLimit, long readGlobalLimit,
238             long writeChannelLimit, long readChannelLimit) {
239         super(writeGlobalLimit, readGlobalLimit);
240         this.writeChannelLimit = writeChannelLimit;
241         this.readChannelLimit = readChannelLimit;
242         createGlobalTrafficCounter(executor);
243     }
244 
245     /**
246      * Create a new instance.
247      *
248      * @param executor
249      *          the {@link ScheduledExecutorService} to use for the {@link TrafficCounter}.
250      * @param checkInterval
251      *          The delay between two computations of performances for
252      *            channels or 0 if no stats are to be computed.
253      */
254     public GlobalChannelTrafficShapingHandler(ScheduledExecutorService executor, long checkInterval) {
255         super(checkInterval);
256         createGlobalTrafficCounter(executor);
257     }
258 
259     /**
260      * Create a new instance.
261      *
262      * @param executor
263      *          the {@link ScheduledExecutorService} to use for the {@link TrafficCounter}.
264      */
265     public GlobalChannelTrafficShapingHandler(ScheduledExecutorService executor) {
266         createGlobalTrafficCounter(executor);
267     }
268 
269     /**
270      * @return the current max deviation
271      */
272     public float maxDeviation() {
273         return maxDeviation;
274     }
275 
276     /**
277      * @return the current acceleration factor
278      */
279     public float accelerationFactor() {
280         return accelerationFactor;
281     }
282 
283     /**
284      * @return the current slow down factor
285      */
286     public float slowDownFactor() {
287         return slowDownFactor;
288     }
289 
290     /**
291      * @param maxDeviation
292      *            the maximum deviation to allow during computation of average, default deviation
293      *            being 0.1, so +/-10% of the desired bandwidth. Maximum being 0.4.
294      * @param slowDownFactor
295      *            the factor set as +x% to the too fast client (minimal value being 0, meaning no
296      *            slow down factor), default being 40% (0.4).
297      * @param accelerationFactor
298      *            the factor set as -x% to the too slow client (maximal value being 0, meaning no
299      *            acceleration factor), default being -10% (-0.1).
300      */
301     public void setMaxDeviation(float maxDeviation, float slowDownFactor, float accelerationFactor) {
302         if (maxDeviation > MAX_DEVIATION) {
303             throw new IllegalArgumentException("maxDeviation must be <= " + MAX_DEVIATION);
304         }
305         checkPositiveOrZero(slowDownFactor, "slowDownFactor");
306         if (accelerationFactor > 0) {
307             throw new IllegalArgumentException("accelerationFactor must be <= 0");
308         }
309         this.maxDeviation = maxDeviation;
310         this.accelerationFactor = 1 + accelerationFactor;
311         this.slowDownFactor = 1 + slowDownFactor;
312     }
313 
314     private void computeDeviationCumulativeBytes() {
315         // compute the maximum cumulativeXxxxBytes among still connected Channels
316         long maxWrittenBytes = 0;
317         long maxReadBytes = 0;
318         long minWrittenBytes = Long.MAX_VALUE;
319         long minReadBytes = Long.MAX_VALUE;
320         for (PerChannel perChannel : channelQueues.values()) {
321             long value = perChannel.channelTrafficCounter.cumulativeWrittenBytes();
322             if (maxWrittenBytes < value) {
323                 maxWrittenBytes = value;
324             }
325             if (minWrittenBytes > value) {
326                 minWrittenBytes = value;
327             }
328             value = perChannel.channelTrafficCounter.cumulativeReadBytes();
329             if (maxReadBytes < value) {
330                 maxReadBytes = value;
331             }
332             if (minReadBytes > value) {
333                 minReadBytes = value;
334             }
335         }
336         boolean multiple = channelQueues.size() > 1;
337         readDeviationActive = multiple && minReadBytes < maxReadBytes / 2;
338         writeDeviationActive = multiple && minWrittenBytes < maxWrittenBytes / 2;
339         cumulativeWrittenBytes.set(maxWrittenBytes);
340         cumulativeReadBytes.set(maxReadBytes);
341     }
342 
343     @Override
344     protected void doAccounting(TrafficCounter counter) {
345         computeDeviationCumulativeBytes();
346         super.doAccounting(counter);
347     }
348 
349     private long computeBalancedWait(float maxLocal, float maxGlobal, long wait) {
350         if (maxGlobal == 0) {
351             // no change
352             return wait;
353         }
354         float ratio = maxLocal / maxGlobal;
355         // if in the boundaries, same value
356         if (ratio > maxDeviation) {
357             if (ratio < 1 - maxDeviation) {
358                 return wait;
359             } else {
360                 ratio = slowDownFactor;
361                 if (wait < MINIMAL_WAIT) {
362                     wait = MINIMAL_WAIT;
363                 }
364             }
365         } else {
366             ratio = accelerationFactor;
367         }
368         return (long) (wait * ratio);
369     }
370 
371     /**
372      * @return the maxGlobalWriteSize
373      */
374     public long getMaxGlobalWriteSize() {
375         return maxGlobalWriteSize;
376     }
377 
378     /**
379      * Note the change will be taken as best effort, meaning
380      * that all already scheduled traffics will not be
381      * changed, but only applied to new traffics.<br>
382      * So the expected usage of this method is to be used not too often,
383      * accordingly to the traffic shaping configuration.
384      *
385      * @param maxGlobalWriteSize the maximum Global Write Size allowed in the buffer
386      *            globally for all channels before write suspended is set.
387      */
388     public void setMaxGlobalWriteSize(long maxGlobalWriteSize) {
389         this.maxGlobalWriteSize = checkPositive(maxGlobalWriteSize, "maxGlobalWriteSize");
390     }
391 
392     /**
393      * @return the global size of the buffers for all queues.
394      */
395     public long queuesSize() {
396         return queuesSize.get();
397     }
398 
399     /**
400      * @param newWriteLimit Channel write limit
401      * @param newReadLimit Channel read limit
402      */
403     public void configureChannel(long newWriteLimit, long newReadLimit) {
404         writeChannelLimit = newWriteLimit;
405         readChannelLimit = newReadLimit;
406         long now = TrafficCounter.milliSecondFromNano();
407         for (PerChannel perChannel : channelQueues.values()) {
408             perChannel.channelTrafficCounter.resetAccounting(now);
409         }
410     }
411 
412     /**
413      * @return Channel write limit
414      */
415     public long getWriteChannelLimit() {
416         return writeChannelLimit;
417     }
418 
419     /**
420      * @param writeLimit Channel write limit
421      */
422     public void setWriteChannelLimit(long writeLimit) {
423         writeChannelLimit = writeLimit;
424         long now = TrafficCounter.milliSecondFromNano();
425         for (PerChannel perChannel : channelQueues.values()) {
426             perChannel.channelTrafficCounter.resetAccounting(now);
427         }
428     }
429 
430     /**
431      * @return Channel read limit
432      */
433     public long getReadChannelLimit() {
434         return readChannelLimit;
435     }
436 
437     /**
438      * @param readLimit Channel read limit
439      */
440     public void setReadChannelLimit(long readLimit) {
441         readChannelLimit = readLimit;
442         long now = TrafficCounter.milliSecondFromNano();
443         for (PerChannel perChannel : channelQueues.values()) {
444             perChannel.channelTrafficCounter.resetAccounting(now);
445         }
446     }
447 
448     /**
449      * Release all internal resources of this instance.
450      */
451     public final void release() {
452         trafficCounter.stop();
453     }
454 
455     private PerChannel getOrSetPerChannel(ChannelHandlerContext ctx) {
456         // ensure creation is limited to one thread per channel
457         Channel channel = ctx.channel();
458         ChannelId key = channel.id();
459         PerChannel perChannel = channelQueues.get(key);
460         if (perChannel == null) {
461             perChannel = new PerChannel();
462             perChannel.messagesQueue = new ArrayDeque<ToSend>();
463             // Don't start it since managed through the Global one
464             perChannel.channelTrafficCounter = new TrafficCounter(this, null, "ChannelTC" +
465                     ctx.channel().id().asShortText(), checkInterval);
466             perChannel.queueSize = 0L;
467             perChannel.lastReadTimestamp = TrafficCounter.milliSecondFromNano();
468             perChannel.lastWriteTimestamp = perChannel.lastReadTimestamp;
469             channelQueues.put(key, perChannel);
470         }
471         return perChannel;
472     }
473 
474     @Override
475     public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
476         getOrSetPerChannel(ctx);
477         trafficCounter.resetCumulativeTime();
478         super.handlerAdded(ctx);
479     }
480 
481     @Override
482     public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
483         trafficCounter.resetCumulativeTime();
484         Channel channel = ctx.channel();
485         ChannelId key = channel.id();
486         PerChannel perChannel = channelQueues.remove(key);
487         if (perChannel != null) {
488             // write operations need synchronization
489             synchronized (perChannel) {
490                 if (channel.isActive()) {
491                     for (ToSend toSend : perChannel.messagesQueue) {
492                         long size = calculateSize(toSend.toSend);
493                         trafficCounter.bytesRealWriteFlowControl(size);
494                         perChannel.channelTrafficCounter.bytesRealWriteFlowControl(size);
495                         perChannel.queueSize -= size;
496                         queuesSize.addAndGet(-size);
497                         ctx.write(toSend.toSend, toSend.promise);
498                     }
499                 } else if (!perChannel.messagesQueue.isEmpty()) {
500                     queuesSize.addAndGet(-perChannel.queueSize);
501                     ClosedChannelException cause = new ClosedChannelException();
502                     for (ToSend toSend : perChannel.messagesQueue) {
503                         releaseAndFailQueuedWrite(toSend.toSend, toSend.promise, cause);
504                     }
505                     perChannel.queueSize = 0;
506                 }
507                 perChannel.messagesQueue.clear();
508             }
509         }
510         releaseWriteSuspended(ctx);
511         releaseReadSuspended(ctx);
512         super.handlerRemoved(ctx);
513     }
514 
515     @Override
516     public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception {
517         long size = calculateSize(msg);
518         long now = TrafficCounter.milliSecondFromNano();
519         if (size > 0) {
520             // compute the number of ms to wait before reopening the channel
521             long waitGlobal = trafficCounter.readTimeToWait(size, getReadLimit(), maxTime, now);
522             ChannelId key = ctx.channel().id();
523             PerChannel perChannel = channelQueues.get(key);
524             long wait = 0;
525             if (perChannel != null) {
526                 wait = perChannel.channelTrafficCounter.readTimeToWait(size, readChannelLimit, maxTime, now);
527                 if (readDeviationActive) {
528                     // now try to balance between the channels
529                     long maxLocalRead;
530                     maxLocalRead = perChannel.channelTrafficCounter.cumulativeReadBytes();
531                     long maxGlobalRead = cumulativeReadBytes.get();
532                     if (maxLocalRead <= 0) {
533                         maxLocalRead = 0;
534                     }
535                     if (maxGlobalRead < maxLocalRead) {
536                         maxGlobalRead = maxLocalRead;
537                     }
538                     wait = computeBalancedWait(maxLocalRead, maxGlobalRead, wait);
539                 }
540             }
541             if (wait < waitGlobal) {
542                 wait = waitGlobal;
543             }
544             wait = checkWaitReadTime(ctx, wait, now);
545             if (wait >= MINIMAL_WAIT) { // At least 10ms seems a minimal
546                 // time in order to try to limit the traffic
547                 // Only AutoRead AND HandlerActive True means Context Active
548                 Channel channel = ctx.channel();
549                 ChannelConfig config = channel.config();
550                 if (logger.isDebugEnabled()) {
551                     logger.debug("Read Suspend: " + wait + ':' + config.isAutoRead() + ':'
552                             + isHandlerActive(ctx));
553                 }
554                 if (config.isAutoRead() && isHandlerActive(ctx)) {
555                     config.setAutoRead(false);
556                     channel.attr(READ_SUSPENDED).set(true);
557                     // Create a Runnable to reactive the read if needed. If one was create before it will just be
558                     // reused to limit object creation
559                     Attribute<Runnable> attr = channel.attr(REOPEN_TASK);
560                     Runnable reopenTask = attr.get();
561                     if (reopenTask == null) {
562                         reopenTask = new ReopenReadTimerTask(ctx);
563                         attr.set(reopenTask);
564                     }
565                     ctx.executor().schedule(reopenTask, wait, TimeUnit.MILLISECONDS);
566                     if (logger.isDebugEnabled()) {
567                         logger.debug("Suspend final status => " + config.isAutoRead() + ':'
568                                 + isHandlerActive(ctx) + " will reopened at: " + wait);
569                     }
570                 }
571             }
572         }
573         informReadOperation(ctx, now);
574         ctx.fireChannelRead(msg);
575     }
576 
577     @Override
578     protected long checkWaitReadTime(final ChannelHandlerContext ctx, long wait, final long now) {
579         ChannelId key = ctx.channel().id();
580         PerChannel perChannel = channelQueues.get(key);
581         if (perChannel != null) {
582             if (wait > maxTime && now + wait - perChannel.lastReadTimestamp > maxTime) {
583                 wait = maxTime;
584             }
585         }
586         return wait;
587     }
588 
589     @Override
590     protected void informReadOperation(final ChannelHandlerContext ctx, final long now) {
591         ChannelId key = ctx.channel().id();
592         PerChannel perChannel = channelQueues.get(key);
593         if (perChannel != null) {
594             perChannel.lastReadTimestamp = now;
595         }
596     }
597 
598     private static final class ToSend {
599         final long relativeTimeAction;
600         final Object toSend;
601         final ChannelPromise promise;
602         final long size;
603 
604         private ToSend(final long delay, final Object toSend, final long size, final ChannelPromise promise) {
605             relativeTimeAction = delay;
606             this.toSend = toSend;
607             this.size = size;
608             this.promise = promise;
609         }
610     }
611 
612     protected long maximumCumulativeWrittenBytes() {
613         return cumulativeWrittenBytes.get();
614     }
615 
616     protected long maximumCumulativeReadBytes() {
617         return cumulativeReadBytes.get();
618     }
619 
620     /**
621      * To allow for instance doAccounting to use the TrafficCounter per channel.
622      * @return the list of TrafficCounters that exists at the time of the call.
623      */
624     public Collection<TrafficCounter> channelTrafficCounters() {
625         return new AbstractCollection<TrafficCounter>() {
626             @Override
627             public Iterator<TrafficCounter> iterator() {
628                 return new Iterator<TrafficCounter>() {
629                     final Iterator<PerChannel> iter = channelQueues.values().iterator();
630                     @Override
631                     public boolean hasNext() {
632                         return iter.hasNext();
633                     }
634                     @Override
635                     public TrafficCounter next() {
636                         return iter.next().channelTrafficCounter;
637                     }
638                     @Override
639                     public void remove() {
640                         throw new UnsupportedOperationException();
641                     }
642                 };
643             }
644             @Override
645             public int size() {
646                 return channelQueues.size();
647             }
648         };
649     }
650 
651     @Override
652     public void write(final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise)
653             throws Exception {
654         long size = calculateSize(msg);
655         long now = TrafficCounter.milliSecondFromNano();
656         if (size > 0) {
657             // compute the number of ms to wait before continue with the channel
658             long waitGlobal = trafficCounter.writeTimeToWait(size, getWriteLimit(), maxTime, now);
659             ChannelId key = ctx.channel().id();
660             PerChannel perChannel = channelQueues.get(key);
661             long wait = 0;
662             if (perChannel != null) {
663                 wait = perChannel.channelTrafficCounter.writeTimeToWait(size, writeChannelLimit, maxTime, now);
664                 if (writeDeviationActive) {
665                     // now try to balance between the channels
666                     long maxLocalWrite;
667                     maxLocalWrite = perChannel.channelTrafficCounter.cumulativeWrittenBytes();
668                     long maxGlobalWrite = cumulativeWrittenBytes.get();
669                     if (maxLocalWrite <= 0) {
670                         maxLocalWrite = 0;
671                     }
672                     if (maxGlobalWrite < maxLocalWrite) {
673                         maxGlobalWrite = maxLocalWrite;
674                     }
675                     wait = computeBalancedWait(maxLocalWrite, maxGlobalWrite, wait);
676                 }
677             }
678             if (wait < waitGlobal) {
679                 wait = waitGlobal;
680             }
681             if (wait >= MINIMAL_WAIT) {
682                 if (logger.isDebugEnabled()) {
683                     logger.debug("Write suspend: " + wait + ':' + ctx.channel().config().isAutoRead() + ':'
684                             + isHandlerActive(ctx));
685                 }
686                 submitWrite(ctx, msg, size, wait, now, promise);
687                 return;
688             }
689         }
690         // to maintain order of write
691         submitWrite(ctx, msg, size, 0, now, promise);
692     }
693 
694     @Override
695     protected void submitWrite(final ChannelHandlerContext ctx, final Object msg,
696             final long size, final long writedelay, final long now,
697             final ChannelPromise promise) {
698         Channel channel = ctx.channel();
699         ChannelId key = channel.id();
700         PerChannel perChannel = channelQueues.get(key);
701         if (perChannel == null) {
702             // in case write occurs before handlerAdded is raised for this handler
703             // imply a synchronized only if needed
704             perChannel = getOrSetPerChannel(ctx);
705         }
706         final ToSend newToSend;
707         long delay = writedelay;
708         boolean globalSizeExceeded = false;
709         // write operations need synchronization
710         synchronized (perChannel) {
711             if (writedelay == 0 && perChannel.messagesQueue.isEmpty()) {
712                 trafficCounter.bytesRealWriteFlowControl(size);
713                 perChannel.channelTrafficCounter.bytesRealWriteFlowControl(size);
714                 ctx.write(msg, promise);
715                 perChannel.lastWriteTimestamp = now;
716                 return;
717             }
718             if (delay > maxTime && now + delay - perChannel.lastWriteTimestamp > maxTime) {
719                 delay = maxTime;
720             }
721             newToSend = new ToSend(delay + now, msg, size, promise);
722             perChannel.messagesQueue.addLast(newToSend);
723             perChannel.queueSize += size;
724             queuesSize.addAndGet(size);
725             checkWriteSuspend(ctx, delay, perChannel.queueSize);
726             if (queuesSize.get() > maxGlobalWriteSize) {
727                 globalSizeExceeded = true;
728             }
729         }
730         if (globalSizeExceeded) {
731             setUserDefinedWritability(ctx, false);
732         }
733         final long futureNow = newToSend.relativeTimeAction;
734         final PerChannel forSchedule = perChannel;
735         ctx.executor().schedule(new Runnable() {
736             @Override
737             public void run() {
738                 sendAllValid(ctx, forSchedule, futureNow);
739             }
740         }, delay, TimeUnit.MILLISECONDS);
741     }
742 
743     private void sendAllValid(final ChannelHandlerContext ctx, final PerChannel perChannel, final long now) {
744         // write operations need synchronization
745         synchronized (perChannel) {
746             ToSend newToSend = perChannel.messagesQueue.pollFirst();
747             for (; newToSend != null; newToSend = perChannel.messagesQueue.pollFirst()) {
748                 if (newToSend.relativeTimeAction <= now) {
749                     long size = newToSend.size;
750                     trafficCounter.bytesRealWriteFlowControl(size);
751                     perChannel.channelTrafficCounter.bytesRealWriteFlowControl(size);
752                     perChannel.queueSize -= size;
753                     queuesSize.addAndGet(-size);
754                     ctx.write(newToSend.toSend, newToSend.promise);
755                     perChannel.lastWriteTimestamp = now;
756                 } else {
757                     perChannel.messagesQueue.addFirst(newToSend);
758                     break;
759                 }
760             }
761             if (perChannel.messagesQueue.isEmpty()) {
762                 releaseWriteSuspended(ctx);
763             }
764         }
765         ctx.flush();
766     }
767 
768     @Override
769     public String toString() {
770         return new StringBuilder(340).append(super.toString())
771             .append(" Write Channel Limit: ").append(writeChannelLimit)
772             .append(" Read Channel Limit: ").append(readChannelLimit).toString();
773     }
774 }