Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tomcat crashes with java.lang.OutOfMemory Error while trying to send an HTTP request

We have a service deployed on Tomcat 8. It usually runs fine, but it is observed that tomcat abruptly crashes sometimes. Today when it did, I found following logs present:

 SEVERE org.apache.tomcat.util.net.NioEndpoint$Acceptor.run 
       java.lang.OutOfMemoryError: Java Heap Space

I figured that, this occurred when the service tried to hit a POST request. The code for the same is as follows:

  URL obj = new URL(url);
  HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
  con.setRequestMethod("POST");
  con.setRequestProperty("User-Agent", USER_AGENT);
  con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

  con.setDoOutput(true);
  DataOutputStream wr = new DataOutputStream(con.getOutputStream());
  wr.writeBytes(urlParameters);
  wr.flush();
  wr.close();

  int responseCode = con.getResponseCode();
  BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
  String inputLine;
  while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
  in.close();

What could be the reason for tomcats' crash? Is it because of any of the following reasons?

  1. Most of the resources like outputstream and inputstream are not closed?
  2. Also the the HttpsURLConnectioncon is not closed/ disconnected?
  3. If so, then why it doesn't happen every time. In fact, this is observed for the first time in more than couple of months.
  4. I also saw that the OME was thrown by ByteArray or something like that. Not sure about that. Just remember seeing something.
  5. Along with the logs, following exception was also seen: Exception in thread "AsyncFileHandlerWriter-#######"

I am stuck at the moment and worried about the thing that, this scenario might occur again. I need to find the root cause for the same. Any help or advice regarding the same would be really useful.

like image 482
theimpatientcoder Avatar asked Oct 22 '25 12:10

theimpatientcoder


1 Answers

Add the following to your jvm arguments:

-Xms512m -Xmx2048m -XX:+HeapDumpOnOutOfMemoryError

The next time an error occurs, you should see a *.hprof file in your startup folder. Use a profiler to open that, my favorites are yjp and mat. Either will show you the top contenders for heap in the application as well as number of threads and resource usage.

Hope this helps.

like image 62
Timir Avatar answered Oct 25 '25 01:10

Timir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!