Skip to content

Commit bd05448

Browse files
authored
minimize the number of times of open/close file (#32)
1 parent bffe481 commit bd05448

File tree

1 file changed

+22
-4
lines changed

1 file changed

+22
-4
lines changed

core/src/main/java/com/segment/analytics/kotlin/core/utilities/EventsFileManager.kt

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
package com.segment.analytics.kotlin.core.utilities
22

3+
import kotlinx.coroutines.runBlocking
34
import java.io.File
45
import java.io.FileOutputStream
56
import java.time.Instant
@@ -39,10 +40,13 @@ class EventsFileManager(
3940

4041
init {
4142
createDirectory(directory)
43+
registerShutdownHook()
4244
}
4345

4446
private val fileIndexKey = "segment.events.file.index.$writeKey"
4547

48+
private var os: FileOutputStream? = null
49+
4650
companion object {
4751
const val MAX_FILE_SIZE = 475_000 // 475KB
4852
}
@@ -120,6 +124,8 @@ class EventsFileManager(
120124
val contents = """],"sentAt":"${Instant.now()}"}"""
121125
writeToFile(contents.toByteArray(), file)
122126
file.renameTo(File(directory, file.nameWithoutExtension))
127+
os?.close()
128+
os = null
123129
incrementFileIndex()
124130
}
125131

@@ -132,10 +138,22 @@ class EventsFileManager(
132138
// Atomic write to underlying file
133139
// TODO make atomic
134140
private fun writeToFile(content: ByteArray, file: File) {
135-
val os = FileOutputStream(file, true)
136-
os.write(content)
137-
os.flush()
138-
os.close()
141+
os = os ?: FileOutputStream(file, true)
142+
os?.run {
143+
write(content)
144+
flush()
145+
}
146+
}
147+
148+
private fun registerShutdownHook() {
149+
// close the stream if the app shuts down
150+
Runtime.getRuntime().addShutdownHook(object : Thread() {
151+
override fun run() {
152+
runBlocking {
153+
os?.close()
154+
}
155+
}
156+
})
139157
}
140158
}
141159

0 commit comments

Comments
 (0)