title: Closing Netty server cleanly
body: <p>Hello currently I am developing an Arquillian extension for Moco framework (<a href="https://github.com/dreamhead/moco" rel="nofollow">https://github.com/dreamhead/moco</a>). Moco is used for testing RESTful services and relies on Netty for dealing with communication. Currently Moco is using Netty 4.0.18.Final.</p>
  
  <p>But I have found a problem when running Moco (and Netty server) inside a container (Arquillian runs tests within the container) and is that it starts correctly but when the application is undeployed and server is shutdown next log error messages are printed:</p>
  
  <p><em>SEVERE: The web application [/ba32e781-3a18-44b3-9547-7c26787f3fe7] appears to have started a thread named [pool-2-thread-1] but has failed to stop it. This is very likely to create a memory leak.
  abr 08, 2014 10:29:06 AM org.apache.catalina.loader.WebappClassLoader checkThreadLocalMapForLeaks
  SEVERE: The web application [/ba32e781-3a18-44b3-9547-7c26787f3fe7] created a ThreadLocal with key of type [io.netty.util.internal.ThreadLocalRandom$2] (value [io.netty.util.internal.ThreadLocalRandom$2@77468cae]) and a value of type [io.netty.util.internal.ThreadLocalRandom] (value [io.netty.util.internal.ThreadLocalRandom@6cd3851]) but failed to remove it when the web application was stopped. Threads are going to be renewed over time to try and avoid a probable memory leak.</em></p>
  
  <p>Basically it seems that there are some threads that are not closed yet when the server tries to shutdown.</p>
  
  <p>From the point of view of Arquillian extension when the application is deployed into the server the start method of Moco is called and before undeploying the application the stop method from Moco is called.</p>
  
  <p>But let me show you the code of Moco:</p>
  
  <pre><code>public int start(final int port, ChannelHandler pipelineFactory) {
      ServerBootstrap bootstrap = new ServerBootstrap();
      bootstrap.group(bossGroup, workerGroup)
               .channel(NioServerSocketChannel.class)
               .childHandler(pipelineFactory);
  
      try {
          future = bootstrap.bind(port).sync();
          SocketAddress socketAddress = future.channel().localAddress();
          address = (InetSocketAddress) socketAddress;
          return address.getPort();
      } catch (InterruptedException e) {
          throw new RuntimeException(e);
      }
  </code></pre>
  
  <p>and the stop method looks like:</p>
  
  <pre><code>private void doStop() {
      if (future != null) {
          future.channel().close().syncUninterruptibly();
          future = null;
      }
  </code></pre>
  
  <p>So it seems that the close method returns before killing all the threads and for this reason containers warns you about possible memory leaks.</p>
  
  <p>Because I have never used Netty I was wondering if there is a way to ensure that the whole Netty runtime is closed.</p>
  
  <p>Thank you so much for your help.</p>