This is the first day of my participation in the August Text Challenge.More challenges in August

I was happily writing code when I received an online alarm. I was out of ram and had less than 1G available memory.

?????

My first reaction was that I didn’t do anything. Why did I call the police? Then operations students threw out this picture:

The available memory for online applications is like that long downhill slope at the edge of high school…

No surprise, memory leaks, 80% of the code I wrote.

Contact o&M and dump two memory snapshots half an hour apart.

I quickly restarted the server to make it better first.

Then I started to analyze the snapshot with MAT, and found that some streams were not closed, resulting in slow memory growth.

Well, this is the main text of the day.

DefaultHttpClient has also been marked as @deprecated and client and Response have not been closed.

public static String sendGet(String url) {
    String res = null;
    try {
        DefaultHttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet(url);
        HttpResponse response = client.execute(request);
        if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { res = EntityUtils.toString(response.getEntity()); }}catch (IOException e) {
        logger.error("Get request submission failed :{}", url, e);
    }
    return res;
}
Copy the code

Then it changed to something like this:

public static String sendGet(String url) {
    String res = null;
    try (CloseableHttpClient client = HttpClients.createDefault()) {
        HttpGet request = new HttpGet(url);
        try (CloseableHttpResponse response = client.execute(request)) {
            if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { res = EntityUtils.toString(response.getEntity()); }}}catch (IOException e) {
        logger.error("Get request submission failed :{}", url, e);
    }
    return res;
}
Copy the code

So here’s the problem, you’re done, you suddenly want to see what the EntityUtils is?

ToString () already knows these methods, so what consume() is all about

/** * Ensures that the entity content is fully consumed and the content stream, if exists, * is closed. * * @param entity the entity to consume. * @throws IOException if an error occurs reading the input stream * * @since 4.1 */ public static void consume(final HttpEntity entity) throws IOException {if (entity == null) {return;  } if (entity.isStreaming()) { final InputStream instream = entity.getContent(); if (instream ! = null) { instream.close(); }}}Copy the code

Oh, wait, this is a method to close the stream, I have not called before ah, not again!!

Take a closer look at toString()

So this place was already closed, so it’s okay.