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.Contract;
35  import org.apache.http.annotation.ThreadingBehavior;
36  import org.apache.http.client.HttpClient;
37  import org.apache.http.client.ResponseHandler;
38  import org.apache.http.client.methods.HttpUriRequest;
39  import org.apache.http.concurrent.FutureCallback;
40  import org.apache.http.protocol.HttpContext;
41  
42  /**
43   * HttpAsyncClientWithFuture wraps calls to execute with a {@link HttpRequestFutureTask}
44   * and schedules them using the provided executor service. Scheduled calls may be cancelled.
45   */
46  @Contract(threading = ThreadingBehavior.SAFE)
47  public class FutureRequestExecutionService implements Closeable {
48  
49      private final HttpClient httpclient;
50      private final ExecutorService executorService;
51      private final FutureRequestExecutionMetricsnMetrics.html#FutureRequestExecutionMetrics">FutureRequestExecutionMetrics metrics = new FutureRequestExecutionMetrics();
52      private final AtomicBoolean closed = new AtomicBoolean(false);
53  
54      /**
55       * Create a new FutureRequestExecutionService.
56       *
57       * @param httpclient
58       *            you should tune your httpclient instance to match your needs. You should
59       *            align the max number of connections in the pool and the number of threads
60       *            in the executor; it doesn't make sense to have more threads than connections
61       *            and if you have less connections than threads, the threads will just end up
62       *            blocking on getting a connection from the pool.
63       * @param executorService
64       *            any executorService will do here. E.g.
65       *            {@link java.util.concurrent.Executors#newFixedThreadPool(int)}
66       */
67      public FutureRequestExecutionService(
68              final HttpClient httpclient,
69              final ExecutorService executorService) {
70          this.httpclient = httpclient;
71          this.executorService = executorService;
72      }
73  
74      /**
75       * Schedule a request for execution.
76       *
77       * @param <T>
78       *
79       * @param request
80       *            request to execute
81       * @param responseHandler
82       *            handler that will process the response.
83       * @return HttpAsyncClientFutureTask for the scheduled request.
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      */
108     public <T> HttpRequestFutureTask<T> execute(
109             final HttpUriRequest request,
110             final HttpContext context,
111             final ResponseHandler<T> responseHandler,
112             final FutureCallback<T> callback) {
113         if(closed.get()) {
114             throw new IllegalStateException("Close has been called on this httpclient instance.");
115         }
116         metrics.getScheduledConnections().incrementAndGet();
117         final HttpRequestTaskCallable<T> callable = new HttpRequestTaskCallable<T>(
118             httpclient, request, context, responseHandler, callback, metrics);
119         final HttpRequestFutureTask<T> httpRequestFutureTask = new HttpRequestFutureTask<T>(
120             request, callable);
121         executorService.execute(httpRequestFutureTask);
122 
123         return httpRequestFutureTask;
124     }
125 
126     /**
127      * @return metrics gathered for this instance.
128      * @see FutureRequestExecutionMetrics
129      */
130     public FutureRequestExecutionMetrics metrics() {
131         return metrics;
132     }
133 
134     @Override
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 }