I use OkHttp to perform an asynchronous request:

 public class Main { private static final OkHttpClient client = new OkHttpClient(); public static void main(String[] args) throws Exception { run(); } public static void run() throws Exception { Request request = new Request.Builder() .url("http://publicobject.com/helloworld.txt") .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { e.printStackTrace(); } @Override public void onResponse(Call call, Response response) throws IOException { if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); Headers responseHeaders = response.headers(); for (int i = 0, size = responseHeaders.size(); i < size; i++) { System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i)); } System.out.println(response.body().string()); } }); } } 

As a result of executing this code, the contents of the response from the server are output to the console, but after that the application does not terminate, although I would like it to complete.

As far as I understand, this is due to the fact that in the process OkHttp creates a stream that, for some reason, does not end automatically.

Question two:

Why is the application not terminating?

How to shut down the application correctly after working out one of the callbacks? System.exit(0); or?

  • How do you verify that the application has terminated? And, actually, why is this necessary? Stop unnecessary services and threads, this will be enough. From the application memory, unload the application itself. - tse
  • "How do you verify that the application has terminated?" - I launch in Intellij IDEA. If the application terminates, the console displays: Process finished with exit code 0 and the application stop button becomes inactive. In this case, the opposite is true: the application runs, displays the result, and everything just hangs on, you can manually Stop using the Stop button. - Burence
  • About why this is necessary - I am confused by the fact that after the logical completion of the application, it remains in memory. It feels like a stream is waiting for something. But I obviously do not create threads, they are controlled by OkHTTP . PS: this is not an android. - Burence
  • Yeah, not an android, just now realized. excuse me. - tse

0