I have a synchronization issue regarding a bind request and a upstream handler that receives a channelBound event. I need to attach an object to the channel before the handler can ever receive the channelBound event due to the fact that the handler needs to use the object to handle the callback. Example below.
Handler example:
public class MyClientHandler extends SimpleChannelUpstreamHandler {
@Override
public void channelBound(ChannelHandlerContext ctx, ChannelStateEvent e) {
/* Problem: This can occur while the channel attachment is still null. */
MyStatefulObject obj = e.getChannel().getAttachment();
/* Do important things with attachment. */
}
}
Main example:
ClientBootstrap bootstrap = ... //Assume this has been configured correctly.
ChannelFuture f = bootstrap.bind(new InetSocketAddress("192.168.0.15", 0));
/* It is possible the boundEvent has already been fired upstream
* by the IO thread when I get here.
*/
f.getChannel().setAttachment(new MyStatefulObject());
Possible Soultions
I’ve come up with a couple of solutions to get around this but they both kind of “smell” which is why I’m here asking if anyone has a clean way of doing this.
Solution 1: Spin or block in the channelBound callback until the attachment is not null. I don’t like this solution because it ties up an I/O worker.
Solution 2: Make MyClientHandler in to a bi-directional handler and get the attachment using a ThreadLocal in a bindRequested downstream callback. I don’t like this because it relies on a Netty implementation detail that the requesting thread is used to fire the bindRequested event.
I find solution 1 to be more tolerable than solution 2. So if that is what I need to do I will.
Is there an easy way to get a channel reference without requesting a bind or connect first?
Yes it is possible that, boundEvent can get the handler before you set the attachment to the channel.
If the attachment is very specific to every channel your opening, then you can register a channel future listener on bind future and set the attachment on operationComplete()
by setting up everything without using BootStraps. Following is a modified version of EchoClient Example, It works fine.