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"
}
How long is the Stack Trace? - I think you may have have a recursion defect.
If there is an
IOExceptionthen your exception handling callsdebugmethod which I think (I cannot see all the code) recurses to callwriteFileagain and if that fails with anotherIOExceptionthen it will loop. Notice that themsggrows each time... in the limit this will except your Heap space for growing that space.Next step in your investigation change
to
i.e. do NOT include the
msgthen the explosion inmsgwon't happen. Or consider not logging this using your custom logger.