First: if you want to determine if you're close to OutOfMemoryError
, then what all you have to do is to compare the current memory with the max memory used by JVM
, and that what you already did.
Second: You want to flush results to file, am wondering why you want to do that just if you close to OutOfMemoryError
, you simply can use something like a FileWriter
which has a buffer, so if the buffer got filled it will flush the results automatically.
Third: don't ever call the GC
explicitly, its a bad practice, optimize your JVM
memory arguments instead:
-Xmx -> this param to set the max memory that the JVM can allocate
-Xms -> the init memory that JVM will allocate on the start up
-XX:MaxPermSize= -> this for the max Permanent Generation memory
Also
-XX:MaxNewSize= -> this need to be 40% from your Xmx value
-XX:NewSize= -> this need to be 40% from your Xmx value
These will speed up the GC.
And -XX:+UseConcMarkSweepGC
to enable using CMS
for the old space.