title: Singleton bootstrap and pipelineFactory on Netty as Tcp Client
body: <p>I'm using Netty to implement a server and a client of a protocol over TCP. At the server side, I created one instance of classes bootStrap and pipelineFactory for each port it listen to, and it works great and quickly. </p>
  
  <p>However at the client side I haven't got a clear idea about how to structure it. I need to open thousand connections to thousands differents destinations. I'm developing the project on Spring Framework so I can easily create singleton bean and inject them as properties. I'm evaluating 3 options:</p>
  
  <ul>
  <li><p>Use a singleton instance of ClientBootstrap and PipelineFactory. Every connection uses some code like this to get a channel:</p>
  
  <pre><code>public Channel connect(final InetSocketAddress serverAddress, final ChannelPipelineFactory pipelineFactory, int timeout, TimeUnit unit) throws InterruptedException {
  ChannelFuture future;
  synchronized (bootstrap){
      bootstrap.setPipelineFactory(pipelineFactory);
      future = bootstrap.connect(serverAddress);
      future.addListener(new ChannelFutureListener() {
          @Override
          public void operationComplete(ChannelFuture future) throws Exception {
              if (future.isSuccess()) {
                  //TODO set here some channelLocal properties I need to configure the session (eg: user, password etc...)
              }
              else{
                  throw new RuntimeException(future.getCause()
                          .getMessage());
              }
          }
      });
  }
  return future.getChannel();
  </code></pre>
  
  <p>}</p></li>
  </ul>
  
  <p>My solution have to be able to configure also the pipeline to enable or disable SSL or log handlers, maybe using this <a href="https://stackoverflow.com/a/14049417/2096052" title="parameters for getpipeline&#40;&#41;">Abe solution to configure getPipeline()</a></p>
  
  <ul>
  <li><p>My second option is to use a singleton instance of ClientBootstrap but create a new PipelineFactory on every outgoing client connection. This helps me to configure the pipeline I have, because I can set properties on the pipelineFactory instance.</p></li>
  <li><p>Third option is to create new bootStrap objects and pipelineFactory on every outgoing connection. This allows me to configure properties like tcp.delay or tcp.keepalive on every connection and allow me to delete the synchronized block on connect method, that could speed up client connections. </p></li>
  </ul>
  
  <p>I think first one is fastest and use the lowest memory, but third one is the most configurable and maybe easy to develop.</p>
  
  <p>Could you give me some advices about pros and cons of this approaches? maybe one of them is wrong?</p>
  
  <p>Thank you very much!  </p>