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 org.jboss.netty.bootstrap.ServerBootstrap;
19  import org.jboss.netty.channel.ChannelFuture;
20  import org.jboss.netty.channel.ChannelFutureListener;
21  import org.jboss.netty.channel.ChannelHandler.Sharable;
22  import org.jboss.netty.channel.ChannelHandlerContext;
23  import org.jboss.netty.channel.ChannelPipeline;
24  import org.jboss.netty.channel.ChannelPipelineFactory;
25  import org.jboss.netty.channel.Channels;
26  import org.jboss.netty.channel.MessageEvent;
27  import org.jboss.netty.channel.SimpleChannelDownstreamHandler;
28  import org.jboss.netty.util.ExternalResourceReleasable;
29  import org.jboss.netty.util.HashedWheelTimer;
30  import org.jboss.netty.util.Timeout;
31  import org.jboss.netty.util.Timer;
32  import org.jboss.netty.util.TimerTask;
33  
34  import java.util.concurrent.TimeUnit;
35  
36  import static org.jboss.netty.channel.Channels.*;
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        fireExceptionCaught(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                 fireWriteTimeOut(ctx);
189             }
190         }
191 
192         private void fireWriteTimeOut(final ChannelHandlerContext ctx) {
193             ctx.getPipeline().execute(new Runnable() {
194 
195                 public void run() {
196                     try {
197                         writeTimedOut(ctx);
198                     } catch (Throwable t) {
199                         fireExceptionCaught(ctx, t);
200                     }
201                 }
202             });
203         }
204     }
205 
206     private static final class TimeoutCanceller implements ChannelFutureListener {
207         private final Timeout timeout;
208 
209         TimeoutCanceller(Timeout timeout) {
210             this.timeout = timeout;
211         }
212 
213         public void operationComplete(ChannelFuture future) throws Exception {
214             timeout.cancel();
215         }
216     }
217 }