Skip to content

Instantly share code, notes, and snippets.

@cgbystrom
Created October 31, 2011 14:50
Show Gist options
  • Save cgbystrom/1327647 to your computer and use it in GitHub Desktop.
Save cgbystrom/1327647 to your computer and use it in GitHub Desktop.
Netty event latency simulator
import org.jboss.netty.channel.*;
import org.jboss.netty.util.HashedWheelTimer;
import org.jboss.netty.util.Timeout;
import org.jboss.netty.util.Timer;
import org.jboss.netty.util.TimerTask;
import java.util.concurrent.TimeUnit;
/**
* Simulates latency of Netty events
*
* Useful when debugging race conditions.
*/
public class LatencySimulatorHandler extends SimpleChannelHandler
{
private static final Timer timer = new HashedWheelTimer();
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
delayUpstream(ctx, e);
}
@Override
public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
delayUpstream(ctx, e);
}
@Override
public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
delayUpstream(ctx, e);
}
@Override
public void writeRequested(final ChannelHandlerContext ctx, final MessageEvent e) throws Exception {
delayDownstream(ctx, e);
}
@Override
public void closeRequested(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
delayDownstream(ctx, e);
}
private void delayDownstream(final ChannelHandlerContext ctx, final ChannelEvent e) {
timer.newTimeout(new TimerTask() {
public void run(Timeout timeout) throws Exception {
ctx.sendDownstream(e);
}
}, 500, TimeUnit.MILLISECONDS);
}
private void delayUpstream(final ChannelHandlerContext ctx, final ChannelEvent e) {
timer.newTimeout(new TimerTask() {
public void run(Timeout timeout) throws Exception {
ctx.sendUpstream(e);
}
}, 500, TimeUnit.MILLISECONDS);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment