0

I'm listening to an event stream using an HttpClient::GET. The HttpResponse is returned as an InputStream, which gets written to by the called server as it has data to write, but the server never actually closes the stream.

My code creates a JsonParser using this InputStream and processes the data as it comes in. However, since this stream is never closed, it hangs on nextToken() when it reaches the logical end:

        while (keepListening()) {
            if (parser.nextToken() == null) {
                return;
            }

            treeNode = parser.readValueAsTree();
            LOGGER.trace("treeNode: {}", treeNode);

            isRequestEnd(treeNode).map(this::reportCoreMsUsed)
                    .map(report -> writeReport(csvPrinter, report, this.reportsWritten % 1000.0 == 0.0));
        }

This causes the thread to hang, stuck waiting for nextToken() to return something, which it never will. It doesn't get interrupted, and I'm not sure how to kill it. It'd be great if I could pass in a timeout to the nextToken() call, but since I can't my application runs indefinitely.

This question is a follow-up to Using Java 11 HttpClient to read chunked data, where more of the client code is referenced.

Any ideas for how to handle this client-side (i.e., in my app code)? I'm open to using a different library.

liltitus27
  • 1,670
  • 5
  • 29
  • 46

1 Answers1

0

Maybe not the nicest solution, but a CompletableFuture can solve the problem:

while (true) { try { CompletableFuture<String> future = new CompletableFuture<>(); Executors.newCachedThreadPool().submit(() -> future.complete(slowFunction())); System.out.println(future.get(3, TimeUnit.SECONDS)); } catch(TimeoutException e) { System.out.println("no result this time"); } }

Here we wait up to 3 seconds on any slow function. Print the result (if any), or print a timeout message if there was no result within the time.

Gergely Bacso
  • 14,243
  • 2
  • 44
  • 64