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);
33 * Maximun number of threads allowed to communicate with the server.
35 public int getMaxThreads() {
40 * Set the maximum number of actively communicating (async) threads allowed.
42 * This has no effect on synchronous communication.
44 public void setMaxThreads(int max) {
49 * Launches or queues an asynchronous request.
51 * If the maximum active thread count has not been reached,
52 * start a new thread and use it to send and receive the request.
53 * The response is passed to the request's HttpRequestHandler
54 * onComplete(). After complete, if the number of active threads
55 * is still lower than the max, one request will be pulled (if
56 * present) from the async queue and fired.
58 * If there are too many active threads, the main request is
59 * pushed onto the async queue for later processing
61 protected void manageAsyncRequest(final HttpRequest request) {
63 if (activeThreads >= maxThreads) {
64 pendingThreadQueue.offer(request);
70 //Send the request receive the response, fire off the next
71 //thread if necessary, then pass the result to the handler
72 Runnable r = new Runnable() {
78 while ((response = request.recv()) != null)
79 request.handler.onResponse(request, response);
81 request.handler.onComplete(request);
83 } catch (Exception ex) {
84 request.handler.onError(request, ex);
87 // server communication has completed
91 if (activeThreads < maxThreads) {
93 manageAsyncRequest(pendingThreadQueue.remove());
94 } catch (java.util.NoSuchElementException ex) {
95 // may have been gobbled by another thread
101 new Thread(r).start();