OutOfMemoryError while writing a file using FileOutputStream

168 views Asked by At

I'm facing an OutOfMemoryError while writing a file which is not reproducible every time but it's happening frequently for few users and I got below error while checking logs.

2023-05-03 12:11:11.257 6986-6986/com.example.dev E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.dev, PID: 6986 java.lang.OutOfMemoryError: Failed to allocate a 265048 byte allocation with 96648 free bytes and 94KB until OOM, max allowed footprint 201326592, growth limit 201326592 at java.util.Arrays.copyOf(Arrays.java:3260) 
at java.lang.AbstractStringBuilder.ensureCapacityInternal(AbstractStringBuilder.java:125) 
at java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:451) 
at java.lang.StringBuilder.append(StringBuilder.java:137) 
at com.TestTracLogger.formatLog(TestTracLogger:97) 
at com.TestTracLogger.writeFile(TestTracLogger:86) 
at com.TestTracLogger.debug(TestTracLogger:64) 
at com.ITestTracLoggerRepresentable$DefaultImpls.debug$default(ITestTracLoggerRepresentable.kt:8) 
at com.TestTracLogger.writeFile(TestTracLogger:90) 

And this error is occurring to infinite. Below mentioned the code where it's pointing out the problem.

    private fun writeFile(tag: String, msg: String, exception: Throwable?) {
    try {
        if (logFileOutputStream != null) {
            logFileOutputStream.write(formatLog(msg).toByteArray())
            logFileOutputStream.flush()
        }
    } catch (e: IOException) {
        debug(TAG, "Error in writing log i.e.($msg) to file " + e.message)
    }
}

private fun formatLog(msg: String): String {
    val dateTime: String =
        DateFormatterUtility.formatDateTimeToString(Date(), "MM/dd/yyyy HH:mm:ss.SSS")
    return "$dateTime : $msg \n"
}
1

There are 1 answers

3
AndrewL On

How long is the Stack Trace? - I think you may have have a recursion defect.

If there is an IOException then your exception handling calls debug method which I think (I cannot see all the code) recurses to call writeFile again and if that fails with another IOException then it will loop. Notice that the msg grows each time... in the limit this will except your Heap space for growing that space.

Next step in your investigation change

debug(TAG, "Error in writing log i.e.($msg) to file " + e.message)

to

debug(TAG, "Error in writing log: " + e.message)

i.e. do NOT include the msg then the explosion in msg won't happen. Or consider not logging this using your custom logger.