View Javadoc

1   /*
2    * ====================================================================
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *   http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing,
14   * software distributed under the License is distributed on an
15   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16   * KIND, either express or implied.  See the License for the
17   * specific language governing permissions and limitations
18   * under the License.
19   * ====================================================================
20   *
21   * This software consists of voluntary contributions made by many
22   * individuals on behalf of the Apache Software Foundation.  For more
23   * information on the Apache Software Foundation, please see
24   * <http://www.apache.org/>.
25   *
26   */
27  package org.apache.http.impl.client;
28  
29  import java.io.Closeable;
30  import java.io.IOException;
31  import java.util.concurrent.ExecutorService;
32  import java.util.concurrent.atomic.AtomicBoolean;
33  
34  import org.apache.http.annotation.ThreadSafe;
35  import org.apache.http.client.HttpClient;
36  import org.apache.http.client.ResponseHandler;
37  import org.apache.http.client.methods.HttpUriRequest;
38  import org.apache.http.concurrent.FutureCallback;
39  import org.apache.http.protocol.HttpContext;
40  
41  /**
42   * HttpAsyncClientWithFuture wraps calls to execute with a {@link HttpRequestFutureTask}
43   * and schedules them using the provided executor service. Scheduled calls may be cancelled.
44   */
45  @ThreadSafe
46  public class FutureRequestExecutionService implements Closeable {
47  
48      private final HttpClient httpclient;
49      private final ExecutorService executorService;
50      private final FutureRequestExecutionMetrics metrics = new FutureRequestExecutionMetrics();
51      private final AtomicBoolean closed = new AtomicBoolean(false);
52  
53      /**
54       * Create a new FutureRequestExecutionService.
55       *
56       * @param httpclient
57       *            you should tune your httpclient instance to match your needs. You should
58       *            align the max number of connections in the pool and the number of threads
59       *            in the executor; it doesn't make sense to have more threads than connections
60       *            and if you have less connections than threads, the threads will just end up
61       *            blocking on getting a connection from the pool.
62       * @param executorService
63       *            any executorService will do here. E.g.
64       *            {@link java.util.concurrent.Executors#newFixedThreadPool(int)}
65       */
66      public FutureRequestExecutionService(
67              final HttpClient httpclient,
68              final ExecutorService executorService) {
69          this.httpclient = httpclient;
70          this.executorService = executorService;
71      }
72  
73      /**
74       * Schedule a request for execution.
75       *
76       * @param <T>
77       *
78       * @param request
79       *            request to execute
80       * @param responseHandler
81       *            handler that will process the response.
82       * @return HttpAsyncClientFutureTask for the scheduled request.
83       * @throws InterruptedException
84       */
85      public <T> HttpRequestFutureTask<T> execute(
86              final HttpUriRequest request,
87              final HttpContext context,
88              final ResponseHandler<T> responseHandler) {
89          return execute(request, context, responseHandler, null);
90      }
91  
92      /**
93       * Schedule a request for execution.
94       *
95       * @param <T>
96       *
97       * @param request
98       *            request to execute
99       * @param context
100      *            optional context; use null if not needed.
101      * @param responseHandler
102      *            handler that will process the response.
103      * @param callback
104      *            callback handler that will be called when the request is scheduled,
105      *            started, completed, failed, or cancelled.
106      * @return HttpAsyncClientFutureTask for the scheduled request.
107      * @throws InterruptedException
108      */
109     public <T> HttpRequestFutureTask<T> execute(
110             final HttpUriRequest request,
111             final HttpContext context,
112             final ResponseHandler<T> responseHandler,
113             final FutureCallback<T> callback) {
114         if(closed.get()) {
115             throw new IllegalStateException("Close has been called on this httpclient instance.");
116         }
117         metrics.getScheduledConnections().incrementAndGet();
118         final HttpRequestTaskCallable<T> callable = new HttpRequestTaskCallable<T>(
119             httpclient, request, context, responseHandler, callback, metrics);
120         final HttpRequestFutureTask<T> httpRequestFutureTask = new HttpRequestFutureTask<T>(
121             request, callable);
122         executorService.execute(httpRequestFutureTask);
123 
124         return httpRequestFutureTask;
125     }
126 
127     /**
128      * @return metrics gathered for this instance.
129      * @see FutureRequestExecutionMetrics
130      */
131     public FutureRequestExecutionMetrics metrics() {
132         return metrics;
133     }
134 
135     public void close() throws IOException {
136         closed.set(true);
137         executorService.shutdownNow();
138         if (httpclient instanceof Closeable) {
139             ((Closeable) httpclient).close();
140         }
141     }
142 }