I just can’t realize why my read time out is not working. All I want to do is just to wait
for 10 seconds for some thread to put message to BlockedQueue<String> and on timeout return some kind of response on client.
public class NioAsynChatPipelineFactory implements ChannelPipelineFactory {
private static Timer timer = new HashedWheelTimer();
private final ChannelHandler timeoutHandler = new ReadTimeoutHandler(timer, 10);
@Override
public ChannelPipeline getPipeline() throws Exception {
ChannelPipeline pipeline = Channels.pipeline();
pipeline.addLast("decoder", new HttpRequestDecoder());
pipeline.addLast("encoder", new HttpResponseEncoder());
pipeline.addLast("handler", new NioAsynChatHandler());
pipeline.addLast("timeout", this.timeoutHandler);
return pipeline;
}
}
Now my handler looks like this.
public class NioAsynChatHandler extends SimpleChannelUpstreamHandler{
@Override
public void handleUpstream(
ChannelHandlerContext ctx, ChannelEvent e) throws Exception {
super.handleUpstream(ctx, e);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
throws Exception {
System.out.println("Exception");
\\writing some kind of response and closing channel.
}
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
Thread thread = new Thread(new ConsmerTask(e.getChannel()));
thread.start();
}
and inside ConsumerTask I’m just waiting for BlockingQueue to get response
public class ConsumerTask implements Runnable{
private Channel channel;
public ConsumerTask(Channel channel){
this.channel = channel;
}
@Override
public void run() {
try{
while(true){
String message = queue.take();
}
} catch(InterruptedException ex){
Thread.currentThread.interrupt();
} finally{
//write something to channel and close it
}
}
My problem is that I don’t see that any excpetion occurs on time out.
What am I doing wrong?
Update:
public static final BlockingQueue<String> blockingQueue = new LinkedBlockingQueue<String>();
Actually my question is more generic, How to close channel on timeout while it is waiting for something in external thread?
Update 2:
Another question: due to the fact that I’m running external thread in Cha would it be better to use OrderedMemoryAwareThreadPoolExecutor in pipeline? Will it increase performance.
It’s basically because you put the
ReadTimeoutHandlerin the wrong position. Please put it in the first position of the pipeline (i.e. before all handlers).