< prev index next >

test/jdk/java/net/httpclient/SmallTimeout.java

Print this page




  23 
  24 import java.io.IOException;
  25 import java.net.ServerSocket;
  26 import java.net.URI;
  27 import jdk.incubator.http.HttpClient;
  28 import jdk.incubator.http.HttpRequest;
  29 import jdk.incubator.http.HttpResponse;
  30 import jdk.incubator.http.HttpTimeoutException;
  31 import java.time.Duration;
  32 import java.util.concurrent.CompletableFuture;
  33 import java.util.concurrent.ExecutorService;
  34 import java.util.concurrent.Executors;
  35 import java.util.concurrent.LinkedBlockingQueue;
  36 import static java.lang.System.out;
  37 import static jdk.incubator.http.HttpResponse.BodyHandler.discard;
  38 
  39 /**
  40  * @test
  41  * @bug 8178147
  42  * @summary Ensures that small timeouts do not cause hangs due to race conditions
  43  * @run main/othervm SmallTimeout
  44  */
  45 
  46 // To enable logging use. Not enabled by default as it changes the dynamics
  47 // of the test.
  48 // @run main/othervm -Djdk.httpclient.HttpClient.log=all,frames:all SmallTimeout
  49 
  50 public class SmallTimeout {
  51 
  52     static int[] TIMEOUTS = {2, 1, 3, 2, 100, 1};
  53 
  54     // A queue for placing timed out requests so that their order can be checked.
  55     static LinkedBlockingQueue<HttpRequest> queue = new LinkedBlockingQueue<>();


















  56 
  57     static volatile boolean error;
  58 
  59     public static void main(String[] args) throws Exception {
  60         HttpClient client = HttpClient.newHttpClient();
  61 
  62         try (ServerSocket ss = new ServerSocket(0, 20)) {
  63             int port = ss.getLocalPort();
  64             URI uri = new URI("http://127.0.0.1:" + port + "/");
  65 
  66             HttpRequest[] requests = new HttpRequest[TIMEOUTS.length];
  67 
  68             out.println("--- TESTING Async");
  69             for (int i = 0; i < TIMEOUTS.length; i++) {
  70                 requests[i] = HttpRequest.newBuilder(uri)
  71                                          .timeout(Duration.ofMillis(TIMEOUTS[i]))
  72                                          .GET()
  73                                          .build();
  74 
  75                 final HttpRequest req = requests[i];
  76                 CompletableFuture<HttpResponse<Object>> response = client
  77                     .sendAsync(req, discard(null))
  78                     .whenComplete((HttpResponse<Object> r, Throwable t) -> {

  79                         if (r != null) {
  80                             out.println("Unexpected response: " + r);

  81                             error = true;
  82                         }
  83                         if (t != null) {
  84                             if (!(t.getCause() instanceof HttpTimeoutException)) {
  85                                 out.println("Wrong exception type:" + t.toString());
  86                                 Throwable c = t.getCause() == null ? t : t.getCause();
  87                                 c.printStackTrace();

  88                                 error = true;
  89                             } else {
  90                                 out.println("Caught expected timeout: " + t.getCause());
  91                             }
  92                         }
  93                         if (t == null && r == null) {
  94                             out.println("Both response and throwable are null!");

  95                             error = true;
  96                         }
  97                         queue.add(req);
  98                     });
  99             }
 100             System.out.println("All requests submitted. Waiting ...");
 101 
 102             checkReturn(requests);
 103 
 104             if (error)
 105                 throw new RuntimeException("Failed. Check output");
 106 
 107             // Repeat blocking in separate threads. Use queue to wait.
 108             out.println("--- TESTING Sync");
 109 
 110             // For running blocking response tasks
 111             ExecutorService executor = Executors.newCachedThreadPool();
 112 
 113             for (int i = 0; i < TIMEOUTS.length; i++) {
 114                 requests[i] = HttpRequest.newBuilder(uri)
 115                                          .timeout(Duration.ofMillis(TIMEOUTS[i]))
 116                                          .GET()
 117                                          .build();
 118 
 119                 final HttpRequest req = requests[i];
 120                 executor.execute(() -> {

 121                     try {
 122                         client.send(req, discard(null));
 123                     } catch (HttpTimeoutException e) {
 124                         out.println("Caught expected timeout: " + e);
 125                         queue.offer(req);
 126                     } catch (IOException | InterruptedException ee) {
 127                         Throwable c = ee.getCause() == null ? ee : ee.getCause();
 128                         c.printStackTrace();

 129                         error = true;


 130                     }
 131                 });
 132             }
 133             System.out.println("All requests submitted. Waiting ...");
 134 
 135             checkReturn(requests);
 136 
 137             executor.shutdownNow();
 138 
 139             if (error)
 140                 throw new RuntimeException("Failed. Check output");
 141 
 142         } finally {
 143             ((ExecutorService) client.executor()).shutdownNow();
 144         }
 145     }
 146 
 147     static void checkReturn(HttpRequest[] requests) throws InterruptedException {
 148         // wait for exceptions and check order

 149         for (int j = 0; j < TIMEOUTS.length; j++) {
 150             HttpRequest req = queue.take();
 151             out.println("Got request from queue " + req + ", order: " + getRequest(req, requests));



 152         }
 153         out.println("Return ok");
 154     }
 155 
 156     /** Returns the index of the request in the array. */
 157     static String getRequest(HttpRequest req, HttpRequest[] requests) {
 158         for (int i=0; i<requests.length; i++) {
 159             if (req == requests[i]) {
 160                 return "r" + i;
 161             }
 162         }
 163         throw new AssertionError("Unknown request: " + req);
 164     }
 165 }


  23 
  24 import java.io.IOException;
  25 import java.net.ServerSocket;
  26 import java.net.URI;
  27 import jdk.incubator.http.HttpClient;
  28 import jdk.incubator.http.HttpRequest;
  29 import jdk.incubator.http.HttpResponse;
  30 import jdk.incubator.http.HttpTimeoutException;
  31 import java.time.Duration;
  32 import java.util.concurrent.CompletableFuture;
  33 import java.util.concurrent.ExecutorService;
  34 import java.util.concurrent.Executors;
  35 import java.util.concurrent.LinkedBlockingQueue;
  36 import static java.lang.System.out;
  37 import static jdk.incubator.http.HttpResponse.BodyHandler.discard;
  38 
  39 /**
  40  * @test
  41  * @bug 8178147
  42  * @summary Ensures that small timeouts do not cause hangs due to race conditions
  43  * @run main/othervm -Djdk.incubator.http.internal.common.DEBUG=true SmallTimeout
  44  */
  45 
  46 // To enable logging use. Not enabled by default as it changes the dynamics
  47 // of the test.
  48 // @run main/othervm -Djdk.httpclient.HttpClient.log=all,frames:all SmallTimeout
  49 
  50 public class SmallTimeout {
  51 
  52     static int[] TIMEOUTS = {2, 1, 3, 2, 100, 1};
  53 
  54     // A queue for placing timed out requests so that their order can be checked.
  55     static LinkedBlockingQueue<HttpResult> queue = new LinkedBlockingQueue<>();
  56 
  57     static final class HttpResult {
  58          final HttpRequest request;
  59          final Throwable   failed;
  60          HttpResult(HttpRequest request, Throwable   failed) {
  61              this.request = request;
  62              this.failed = failed;
  63          }
  64 
  65          static HttpResult of(HttpRequest request) {
  66              return new HttpResult(request, null);
  67          }
  68 
  69          static HttpResult of(HttpRequest request, Throwable t) {
  70              return new HttpResult(request, t);
  71          }
  72 
  73     }
  74 
  75     static volatile boolean error;
  76 
  77     public static void main(String[] args) throws Exception {
  78         HttpClient client = HttpClient.newHttpClient();
  79 
  80         try (ServerSocket ss = new ServerSocket(0, 20)) {
  81             int port = ss.getLocalPort();
  82             URI uri = new URI("http://127.0.0.1:" + port + "/");
  83 
  84             HttpRequest[] requests = new HttpRequest[TIMEOUTS.length];
  85 
  86             out.println("--- TESTING Async");
  87             for (int i = 0; i < TIMEOUTS.length; i++) {
  88                 requests[i] = HttpRequest.newBuilder(uri)
  89                                          .timeout(Duration.ofMillis(TIMEOUTS[i]))
  90                                          .GET()
  91                                          .build();
  92 
  93                 final HttpRequest req = requests[i];
  94                 CompletableFuture<HttpResponse<Object>> response = client
  95                     .sendAsync(req, discard(null))
  96                     .whenComplete((HttpResponse<Object> r, Throwable t) -> {
  97                         Throwable cause = null;
  98                         if (r != null) {
  99                             out.println("Unexpected response: " + r);
 100                             cause = new RuntimeException("Unexpected response");
 101                             error = true;
 102                         }
 103                         if (t != null) {
 104                             if (!(t.getCause() instanceof HttpTimeoutException)) {
 105                                 out.println("Wrong exception type:" + t.toString());
 106                                 Throwable c = t.getCause() == null ? t : t.getCause();
 107                                 c.printStackTrace();
 108                                 cause = c;
 109                                 error = true;
 110                             } else {
 111                                 out.println("Caught expected timeout: " + t.getCause());
 112                             }
 113                         }
 114                         if (t == null && r == null) {
 115                             out.println("Both response and throwable are null!");
 116                             cause = new RuntimeException("Both response and throwable are null!");
 117                             error = true;
 118                         }
 119                         queue.add(HttpResult.of(req,cause));
 120                     });
 121             }
 122             System.out.println("All requests submitted. Waiting ...");
 123 
 124             checkReturn(requests);
 125 
 126             if (error)
 127                 throw new RuntimeException("Failed. Check output");
 128 
 129             // Repeat blocking in separate threads. Use queue to wait.
 130             out.println("--- TESTING Sync");
 131 
 132             // For running blocking response tasks
 133             ExecutorService executor = Executors.newCachedThreadPool();
 134 
 135             for (int i = 0; i < TIMEOUTS.length; i++) {
 136                 requests[i] = HttpRequest.newBuilder(uri)
 137                                          .timeout(Duration.ofMillis(TIMEOUTS[i]))
 138                                          .GET()
 139                                          .build();
 140 
 141                 final HttpRequest req = requests[i];
 142                 executor.execute(() -> {
 143                     Throwable cause = null;
 144                     try {
 145                         client.send(req, discard(null));
 146                     } catch (HttpTimeoutException e) {
 147                         out.println("Caught expected timeout: " + e);
 148                     } catch (Throwable ee) {

 149                         Throwable c = ee.getCause() == null ? ee : ee.getCause();
 150                         c.printStackTrace();
 151                         cause = c;
 152                         error = true;
 153                     } finally {
 154                         queue.offer(HttpResult.of(req, cause));
 155                     }
 156                 });
 157             }
 158             System.out.println("All requests submitted. Waiting ...");
 159 
 160             checkReturn(requests);
 161 
 162             executor.shutdownNow();
 163 
 164             if (error)
 165                 throw new RuntimeException("Failed. Check output");
 166 


 167         }
 168     }
 169 
 170     static void checkReturn(HttpRequest[] requests) throws InterruptedException {
 171         // wait for exceptions and check order
 172         boolean ok = true;
 173         for (int j = 0; j < TIMEOUTS.length; j++) {
 174             HttpResult res = queue.take();
 175             HttpRequest req = res.request;
 176             out.println("Got request from queue " + req + ", order: " + getRequest(req, requests)
 177                          + (res.failed == null ? "" : " failed: " + res.failed));
 178             ok = ok && res.failed == null;
 179         }
 180         out.println("Return " + (ok ? "ok" : "nok"));
 181     }
 182 
 183     /** Returns the index of the request in the array. */
 184     static String getRequest(HttpRequest req, HttpRequest[] requests) {
 185         for (int i=0; i<requests.length; i++) {
 186             if (req == requests[i]) {
 187                 return "r" + i;
 188             }
 189         }
 190         throw new AssertionError("Unknown request: " + req);
 191     }
 192 }
< prev index next >