HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Netty connecting to multiple servers

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
connectingnettymultipleservers

Problem

I am using netty to connect to multiple servers, query for an item, and aggregate the results in my Client. The code below works, but I am unsure if it is the best way of achieving my goal. Also, I'm not sure how I should be closing the futures. Could anyone provide guidance? I am using Netty 4.0.25.Final.

public void start() throws InterruptedException
   {
      EventLoopGroup group = new NioEventLoopGroup();
      try
      {
         ArrayList channelFutures = null;
         for (MyServerOject server : servers)
         {
            Bootstrap b = new Bootstrap();
            b.group(group)
                     .channel(NioSocketChannel.class)
                     .option(ChannelOption.TCP_NODELAY, true)
                     .handler(new ChannelInitializer() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception
                        {
                           ChannelPipeline pipeline = ch.pipeline();
                           pipeline.addLast(new myClientHandler(server));
                        }
                     });

            channelFutures = new ArrayList<>();
            ChannelFuture future = b.connect(server.getHost(), server.getPort()).sync();
            channelFutures.add(future);
         }

         for (ChannelFuture channelFuture : channelFutures)
         {
            channelFuture.channel().closeFuture().sync();
         }
      }
      finally
      {
         group.shutdownGracefully();
      }

Solution

Some issues with your code

-
The biggest is that you are creating a
new ArrayList with each interruption of your server. You probably
want to allocate that array outside the loop that is creating the clients and then add each future to that look as they are created.

-
I'd avoid the "sync" in the for loop waiting for things to
get done. If you need to wait for them to complete, attache a
promise listener to each of the futures with a little lambda
function to do whatever it is you need done when the clients are
finished.

-
I'd pass shutdown gracefully a time limit rather than just
waiting forever.

Without more of your code, its hard to say what else you have
overlooked.

Context

StackExchange Code Review Q#83004, answer score: 2

Revisions (0)

No revisions yet.