View Javadoc

    1   /*
    2    * Copyright 2012 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    *   http://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 org.jboss.netty.handler.timeout;
    17
    18  import static org.jboss.netty.channel.Channels.*;
    19
    20  import java.util.concurrent.TimeUnit;
    21
    22  import org.jboss.netty.bootstrap.ServerBootstrap;
    23  import org.jboss.netty.channel.ChannelFuture;
    24  import org.jboss.netty.channel.ChannelFutureListener;
    25  import org.jboss.netty.channel.ChannelHandler.Sharable;
    26  import org.jboss.netty.channel.ChannelHandlerContext;
    27  import org.jboss.netty.channel.ChannelPipeline;
    28  import org.jboss.netty.channel.ChannelPipelineFactory;
    29  import org.jboss.netty.channel.Channels;
    30  import org.jboss.netty.channel.MessageEvent;
    31  import org.jboss.netty.channel.SimpleChannelDownstreamHandler;
    32  import org.jboss.netty.util.ExternalResourceReleasable;
    33  import org.jboss.netty.util.HashedWheelTimer;
    34  import org.jboss.netty.util.Timeout;
    35  import org.jboss.netty.util.Timer;
    36  import org.jboss.netty.util.TimerTask;
    37
    38  /**
    39   * Raises a {@link WriteTimeoutException} when no data was written within a
    40   * certain period of time.
    41   *
    42   * <pre>
    43   * public class MyPipelineFactory implements {@link ChannelPipelineFactory} {
    44   *
    45   *     private final {@link Timer} timer;
    46   *
    47   *     public MyPipelineFactory({@link Timer} timer) {
    48   *         this.timer = timer;
    49   *     }
    50   *
    51   *     public {@link ChannelPipeline} getPipeline() {
    52   *         // An example configuration that implements 30-second write timeout:
    53   *         return {@link Channels}.pipeline(
    54   *             <b>new {@link WriteTimeoutHandler}(timer, 30), // timer must be shared.</b>
    55   *             new MyHandler());
    56   *     }
    57   * }
    58   *
    59   * {@link ServerBootstrap} bootstrap = ...;
    60   * {@link Timer} timer = new {@link HashedWheelTimer}();
    61   * ...
    62   * bootstrap.setPipelineFactory(new MyPipelineFactory(timer));
    63   * </pre>
    64   *
    65   * The {@link Timer} which was specified when the {@link ReadTimeoutHandler} is
    66   * created should be stopped manually by calling {@link #releaseExternalResources()}
    67   * or {@link Timer#stop()} when your application shuts down.
    68   * @see ReadTimeoutHandler
    69   * @see IdleStateHandler
    70   *
    71   * @apiviz.landmark
    72   * @apiviz.uses org.jboss.netty.util.HashedWheelTimer
    73   * @apiviz.has org.jboss.netty.handler.timeout.TimeoutException oneway - - raises
    74   */
    75  @Sharable
    76  public class WriteTimeoutHandler extends SimpleChannelDownstreamHandler
    77                                   implements ExternalResourceReleasable {
    78
    79      static final WriteTimeoutException EXCEPTION = new WriteTimeoutException();
    80
    81      private final Timer timer;
    82      private final long timeoutMillis;
    83
    84      /**
    85       * Creates a new instance.
    86       *
    87       * @param timer
    88       *        the {@link Timer} that is used to trigger the scheduled event.
    89       *        The recommended {@link Timer} implementation is {@link HashedWheelTimer}.
    90       * @param timeoutSeconds
    91       *        write timeout in seconds
    92       */
    93      public WriteTimeoutHandler(Timer timer, int timeoutSeconds) {
    94          this(timer, timeoutSeconds, TimeUnit.SECONDS);
    95      }
    96
    97      /**
    98       * Creates a new instance.
    99       *
    100      * @param timer
    101      *        the {@link Timer} that is used to trigger the scheduled event.
    102      *        The recommended {@link Timer} implementation is {@link HashedWheelTimer}.
    103      * @param timeout
    104      *        write timeout
    105      * @param unit
    106      *        the {@link TimeUnit} of {@code timeout}
    107      */
    108     public WriteTimeoutHandler(Timer timer, long timeout, TimeUnit unit) {
    109         if (timer == null) {
    110             throw new NullPointerException("timer");
    111         }
    112         if (unit == null) {
    113             throw new NullPointerException("unit");
    114         }
    115
    116         this.timer = timer;
    117         if (timeout <= 0) {
    118             timeoutMillis = 0;
    119         } else {
    120             timeoutMillis = Math.max(unit.toMillis(timeout), 1);
    121         }
    122     }
    123
    124     /**
    125      * Stops the {@link Timer} which was specified in the constructor of this
    126      * handler.  You should not call this method if the {@link Timer} is in use
    127      * by other objects.
    128      */
    129     public void releaseExternalResources() {
    130         timer.stop();
    131     }
    132
    133     /**
    134      * Returns the write timeout of the specified event.  By default, this method returns the
    135      * timeout value you specified in the constructor.  Override this method to determine the
    136      * timeout value depending on the message being written.
    137      *
    138      * @param e the message being written
    139      */
    140     protected long getTimeoutMillis(MessageEvent e) {
    141         return timeoutMillis;
    142     }
    143
    144     @Override
    145     public void writeRequested(ChannelHandlerContext ctx, MessageEvent e)
    146             throws Exception {
    147
    148         long timeoutMillis = getTimeoutMillis(e);
    149         if (timeoutMillis > 0) {
    150             // Set timeout only when getTimeoutMillis() returns a positive value.
    151             ChannelFuture future = e.getFuture();
    152             final Timeout timeout = timer.newTimeout(
    153                     new WriteTimeoutTask(ctx, future),
    154                     timeoutMillis, TimeUnit.MILLISECONDS);
    155
    156             future.addListener(new TimeoutCanceller(timeout));
    157         }
    158
    159         super.writeRequested(ctx, e);
    160     }
    161
    162     protected void writeTimedOut(ChannelHandlerContext ctx) throws Exception {
    163        Channels.fireExceptionCaughtLater(ctx, EXCEPTION);
    164     }
    165
    166     private final class WriteTimeoutTask implements TimerTask {
    167
    168         private final ChannelHandlerContext ctx;
    169         private final ChannelFuture future;
    170
    171         WriteTimeoutTask(ChannelHandlerContext ctx, ChannelFuture future) {
    172             this.ctx = ctx;
    173             this.future = future;
    174         }
    175
    176         public void run(Timeout timeout) throws Exception {
    177             if (timeout.isCancelled()) {
    178                 return;
    179             }
    180
    181             if (!ctx.getChannel().isOpen()) {
    182                 return;
    183             }
    184
    185             // Mark the future as failure
    186             if (future.setFailure(EXCEPTION)) {
    187                 // If succeeded to mark as failure, notify the pipeline, too.
    188                 try {
    189                     writeTimedOut(ctx);
    190                 } catch (Throwable t) {
    191                     fireExceptionCaught(ctx, t);
    192                 }
    193             }
    194         }
    195     }
    196
    197     private static final class TimeoutCanceller implements ChannelFutureListener {
    198         private final Timeout timeout;
    199
    200         TimeoutCanceller(Timeout timeout) {
    201             this.timeout = timeout;
    202         }
    203
    204         public void operationComplete(ChannelFuture future) throws Exception {
    205             timeout.cancel();
    206         }
    207     }
    208 }