title: Asynchronous update of promise in Netty Nio
body: <p>I have got a server and client architecture that exchange information. I want to return from the server the number of connected channels. I want to return the message of the server to the clients using promise. My code is:</p>
  
  <pre><code>public static void callBack () throws Exception{
  
     String host = "localhost";
     int port = 8080;
  
     try {
         Bootstrap b = new Bootstrap();
         b.group(workerGroup);
         b.channel(NioSocketChannel.class);
         b.option(ChannelOption.SO_KEEPALIVE, true);
         b.handler(new ChannelInitializer&lt;SocketChannel&gt;() {
          @Override
             public void initChannel(SocketChannel ch) throws Exception {
              ch.pipeline().addLast(new RequestDataEncoder(), new ResponseDataDecoder(), new ClientHandler(promise));
             }
         });
         ChannelFuture f = b.connect(host, port).sync();
         //f.channel().closeFuture().sync();
     }
     finally {
      //workerGroup.shutdownGracefully();
     }
  }
  
  public static void main(String[] args) throws Exception {
  
    callBack();
    while (true) {
  
      Object msg = promise.get();
      System.out.println("The number if the connected clients is not two");
      int ret = Integer.parseInt(msg.toString());
      if (ret == 2){
          break;
      }
    }
    System.out.println("The number if the connected clients is two");
  }
  </code></pre>
  
  <p>When I run one client it is always receiving the message <code>The number if the connected clients is not two</code> and the returning number is always one. When I run a second client it is receiving always as a returning value two, however, the first client still is receiving one. I cannot find which is the correct way to update the promise for the case of the first client.</p>
  
  <p><strong>EDIT:</strong>
  Client Server:</p>
  
  <pre><code>public class ClientHandler extends ChannelInboundHandlerAdapter {
    public final Promise&lt;Object&gt; promise;
    public ClientHandler(Promise&lt;Object&gt; promise) {
        this.promise = promise;
    }
  
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        RequestData msg = new RequestData();
        msg.setIntValue(123);
        msg.setStringValue("all work and no play makes jack a dull boy");
        ctx.writeAndFlush(msg);
    }
  
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println(msg);
        promise.trySuccess(msg);
    }
  } 
  </code></pre>
  
  <p>The code from the client handler storing the message received from server to the promise.</p>