Search code examples
javaheap-dump

how to discover where my app opens more files (Too many open files)?


I did a script to execute every 10 minutes and when the files open on my Java app is greater than 10000 it will execute a jmap command to give to me a heapdump.

My intention is to discover which class of my app is not closing the files or where there is a memory leak or why I receive the message "Too many files open" after 20 hours executing it.

This is my script. Does anybody have other ways or tools to discover where my app is not closing the files? Thanks a lot!

#!/bin/bash

rm openfiles.log
flag=1
for (( ; ; ))
do
   sleep 10m
   files=`ps -A x |grep iscsi | awk '{print $1}' | xargs -I '{}' ls /proc/29192/fd  | wc -l`
   msg="open files: $files - date: `date`"
   echo "$msg     - infinite loops [ hit CTRL+C to stop]"
   echo $msg >> openfiles.log

   if [ $files -gt 10000 ] && [ $flag -eq 1 ]
   then
      jmap -F -dump:file=heapdump.hprof 29192
      flag=0;
      echo "############################################ heapdump of 29192" >> openfiles.log
   fi
   echo "" >> openfiles.log
done

Solution

  • Take a look at File Leak Detector written by Kohsuke Kawaguchi of Jenkins fame. It is a java agent that you attach to your java process.

    There are also other ways to scan for them via FindBugs/PMD, etc. I'd take a look at SonarQube. There are rules specifically about not closing resources.