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       */
84      public <T> HttpRequestFutureTask<T> execute(
85              final HttpUriRequest request,
86              final HttpContext context,
87              final ResponseHandler<T> responseHandler) {
88          return execute(request, context, responseHandler, null);
89      }
90  
91      /**
92       * Schedule a request for execution.
93       *
94       * @param <T>
95       *
96       * @param request
97       *            request to execute
98       * @param context
99       *            optional context; use null if not needed.
100      * @param responseHandler
101      *            handler that will process the response.
102      * @param callback
103      *            callback handler that will be called when the request is scheduled,
104      *            started, completed, failed, or cancelled.
105      * @return HttpAsyncClientFutureTask for the scheduled request.
106      */
107     public <T> HttpRequestFutureTask<T> execute(
108             final HttpUriRequest request,
109             final HttpContext context,
110             final ResponseHandler<T> responseHandler,
111             final FutureCallback<T> callback) {
112         if(closed.get()) {
113             throw new IllegalStateException("Close has been called on this httpclient instance.");
114         }
115         metrics.getScheduledConnections().incrementAndGet();
116         final HttpRequestTaskCallable<T> callable = new HttpRequestTaskCallable<T>(
117             httpclient, request, context, responseHandler, callback, metrics);
118         final HttpRequestFutureTask<T> httpRequestFutureTask = new HttpRequestFutureTask<T>(
119             request, callable);
120         executorService.execute(httpRequestFutureTask);
121 
122         return httpRequestFutureTask;
123     }
124 
125     /**
126      * @return metrics gathered for this instance.
127      * @see FutureRequestExecutionMetrics
128      */
129     public FutureRequestExecutionMetrics metrics() {
130         return metrics;
131     }
132 
133     @Override
134     public void close() throws IOException {
135         closed.set(true);
136         executorService.shutdownNow();
137         if (httpclient instanceof Closeable) {
138             ((Closeable) httpclient).close();
139         }
140     }
141 }