1 package org.opensrf.net.http;
4 import java.net.MalformedURLException;
5 import java.util.Queue;
6 import java.util.concurrent.ConcurrentLinkedQueue;
8 import org.opensrf.util.*;
12 * Manages connection parameters and thread limiting for opensrf json gateway connections.
15 public class HttpConnection {
17 /** Compiled URL object */
19 /** Number of threads currently communicating with the server */
20 protected int activeThreads;
21 /** Queue of pending async requests */
22 protected Queue<HttpRequest> pendingThreadQueue;
23 /** maximum number of actively communicating threads allowed */
24 protected int maxThreads = 10;
26 public HttpConnection(String fullUrl) throws java.net.MalformedURLException {
28 pendingThreadQueue = new ConcurrentLinkedQueue();
29 url = new URL(fullUrl);
32 public int getMaxThreads() {
37 * Set the maximum number of actively communicating threads allowed
39 public void setMaxThreads(int max) {
44 * Launches or queues an asynchronous request.
46 * If the maximum active thread count has not been reached,
47 * start a new thread and use it to send and receive the request.
48 * The response is passed to the request's HttpRequestHandler
49 * onComplete(). After complete, if the number of active threads
50 * is still lower than the max, one request will be pulled (if
51 * present) from the async queue and fired.
53 * If there are too many active threads, the main request is
54 * pushed onto the async queue for later processing
56 protected void manageAsyncRequest(final HttpRequest request) {
58 if (activeThreads >= maxThreads) {
59 pendingThreadQueue.offer(request);
65 //Send the request receive the response, fire off the next
66 //thread if necessary, then pass the result to the handler
67 Runnable r = new Runnable() {
73 while ((response = request.recv()) != null) {
74 if (request.handler != null)
75 request.handler.onResponse(request, response);
78 if (request.handler != null)
79 request.handler.onComplete(request);
83 if (activeThreads < maxThreads) {
85 manageAsyncRequest(pendingThreadQueue.remove());
86 } catch (java.util.NoSuchElementException ex) {
87 // may have been gobbled by another thread
93 new Thread(r).start();