title: How do I kill Apache HttpClient I/O Dispatcher threads after main() exits?
body: <p>I'm using Spring's <a href="http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/client/AsyncRestTemplate.html" rel="nofollow noreferrer">AsyncRestTemplate</a> backed by Apache <a href="https://hc.apache.org/httpcomponents-asyncclient-4.1.x/httpasyncclient/apidocs/org/apache/http/impl/nio/client/CloseableHttpAsyncClient.html" rel="nofollow noreferrer">HttpAsyncClient</a>. My configuration is based on this <a href="http://vincentdevillers.blogspot.com/2013/10/a-best-spring-asyncresttemplate.html" rel="nofollow noreferrer">blog entry</a>.</p>
  
  <p>When running my asynchronous code in JUnit, everything exits cleanly. I suspect this is because JUnit kills all running threads when the test method exits.</p>
  
  <pre><code>@Test
  public void loadFirstSISOfferingFromFactory() throws Exception {
      CourseOfferingService factoryCourseService = ValenceServiceFactory.getCourseOfferingService();
      BlockingQueue&lt;CourseOffering&gt; queue = factoryCourseService.getAllCourseOfferings();
      CourseOffering course = queue.take();
      LOG.info( course.toString() );
  }
  </code></pre>
  
  <p>When I run this same test in a main() method (as it will be when deployed), the I/O dispatcher threads fail to exit.</p>
  
  <pre><code>public static void main( final String args[] ) throws Exception {
      CourseOfferingService courseService = ValenceServiceFactory.getCourseOfferingService();
  
      BlockingQueue&lt;CourseOffering&gt; queue = courseService.getAllCourseOfferings();
      CourseOffering course = queue.take();
      System.out.println( course.toString() );
  }
  </code></pre>
  
  <p>The code works correctly – that is, it connects to the REST API I expect, loads the correct data, executes the callback method, and populates the queue. The ValenceServiceFactory generates Spring beans (I'm using this so non-Spring enabled projects to access my services). However, when all the connections are idle and the main thread has completed, the I/O dispatcher threads live on.</p>
  
  <p><img src="https://i.stack.imgur.com/23bJO.png" alt="IO dispatcher threads in the debugger"></p>
  
  <p>Here's my Spring Configuration:</p>
  
  <pre><code>@Bean
  public RestTemplate restTemplate() {
      RestTemplate restTemplate = new RestTemplate( new HttpComponentsClientHttpRequestFactory() );
      restTemplate.setErrorHandler( new DefaultResponseErrorHandler() {
          @Override
          public void handleError( ClientHttpResponse response ) throws IOException {
              // Do nothing when error is found.
              // Hopefully the status code will be passed to the ResponseEntity
          }
      } );
  
      return restTemplate;
  }
  
  @Bean
  public AsyncRestTemplate asyncRestTemplate() throws IOReactorException {
  
      // Configure Apache Http Client
      PoolingNHttpClientConnectionManager connectionManager = new PoolingNHttpClientConnectionManager( //
              new DefaultConnectingIOReactor( IOReactorConfig.DEFAULT ) );
      connectionManager.setMaxTotal( 1000 ); //Total Connections
      connectionManager.setDefaultMaxPerRoute( 900 ); //Max connections per host
  
      RequestConfig config = RequestConfig.custom() //
              .setConnectTimeout( 60 * 1000 ) // milliseconds
              .build();
  
      CloseableHttpAsyncClient httpclient = HttpAsyncClientBuilder.create() //
              .setConnectionManager( connectionManager ) //
              .setDefaultRequestConfig( config ) //
              .build();
  
      AsyncRestTemplate restTemplate = new AsyncRestTemplate( //
              new HttpComponentsAsyncClientHttpRequestFactory( httpclient ), restTemplate() );
  
      return restTemplate;
  }
  </code></pre>
  
  <p>I suppose dropping a <code>System.exit(0)</code> at the end of the main method, but if there's a running background process I <em>want</em> to complete, it'll be killed immediately, rather than waiting to complete.</p>
  
  <p>Essentially, I'm looking for an equivalent of <code>java.util.concurrent.ExecutorService.shutdown()</code> and <code>.awaitTermination()</code>, except for AsyncRestTemplate or HttpAsyncClient. In theory, a clean shutdown would be possible after each dispatcher thread has been idle a certain time. </p>
  
  <p>Is that possible? Am I forced to use <code>System.exit()</code>?</p>
  
  <p>Thanks in advance.</p>