test/jdk/java/net/httpclient/SmallTimeout.java
changeset 47216 71c04702a3d5
parent 44639 5c2838d882a5
child 48083 b1c1b4ef4be2
equal deleted inserted replaced
47215:4ebc2e2fb97c 47216:71c04702a3d5
       
     1 /*
       
     2  * Copyright (c) 2015, 2017, Oracle and/or its affiliates. All rights reserved.
       
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
       
     4  *
       
     5  * This code is free software; you can redistribute it and/or modify it
       
     6  * under the terms of the GNU General Public License version 2 only, as
       
     7  * published by the Free Software Foundation.
       
     8  *
       
     9  * This code is distributed in the hope that it will be useful, but WITHOUT
       
    10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
       
    11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
       
    12  * version 2 for more details (a copy is included in the LICENSE file that
       
    13  * accompanied this code).
       
    14  *
       
    15  * You should have received a copy of the GNU General Public License version
       
    16  * 2 along with this work; if not, write to the Free Software Foundation,
       
    17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
       
    18  *
       
    19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
       
    20  * or visit www.oracle.com if you need additional information or have any
       
    21  * questions.
       
    22  */
       
    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 }