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
24import java.io.IOException;
25import java.net.ServerSocket;
26import java.net.URI;
27import jdk.incubator.http.HttpClient;
28import jdk.incubator.http.HttpRequest;
29import jdk.incubator.http.HttpResponse;
30import jdk.incubator.http.HttpTimeoutException;
31import java.time.Duration;
32import java.util.concurrent.CompletableFuture;
33import java.util.concurrent.ExecutorService;
34import java.util.concurrent.Executors;
35import java.util.concurrent.LinkedBlockingQueue;
36import static java.lang.System.out;
37import 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
50public 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}
166