title: How attach an object to a channel before handlers receive events with Netty?
body: <p>I have a synchronization issue regarding a bind request and a upstream handler that receives a <code>channelBound</code> event. I need to attach an object to the channel before the handler can ever receive the <code>channelBound</code> event due to the fact that the handler needs to use the object to handle the callback. Example below.</p>
  
  <p>Handler example:</p>
  
  <pre><code>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. */ 
      }
  
  }
  </code></pre>
  
  <p>Main example:</p>
  
  <pre><code>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());
  </code></pre>
  
  <p><strong>Possible Soultions</strong></p>
  
  <p>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.</p>
  
  <p>Solution 1: Spin or block in the <code>channelBound</code> callback until the attachment is not null. I don't like this solution because it ties up an I/O worker.</p>
  
  <p>Solution 2: Make <code>MyClientHandler</code> in to a bi-directional handler and get the attachment using a <code>ThreadLocal</code> in a <code>bindRequested</code> downstream callback. I don't like this because it relies on a Netty implementation detail that the requesting thread is used to fire the <code>bindRequested</code> event.</p>
  
  <p>I find solution 1 to be more tolerable than solution 2. So if that is what I need to do I will.</p>
  
  <p>Is there an easy way to get a channel reference without requesting a bind or connect first?</p>