File tree Expand file tree Collapse file tree 1 file changed +22
-4
lines changed
core/src/main/java/com/segment/analytics/kotlin/core/utilities Expand file tree Collapse file tree 1 file changed +22
-4
lines changed Original file line number Diff line number Diff line change 1
1
package com.segment.analytics.kotlin.core.utilities
2
2
3
+ import kotlinx.coroutines.runBlocking
3
4
import java.io.File
4
5
import java.io.FileOutputStream
5
6
import java.time.Instant
@@ -39,10 +40,13 @@ class EventsFileManager(
39
40
40
41
init {
41
42
createDirectory(directory)
43
+ registerShutdownHook()
42
44
}
43
45
44
46
private val fileIndexKey = " segment.events.file.index.$writeKey "
45
47
48
+ private var os: FileOutputStream ? = null
49
+
46
50
companion object {
47
51
const val MAX_FILE_SIZE = 475_000 // 475KB
48
52
}
@@ -120,6 +124,8 @@ class EventsFileManager(
120
124
val contents = """ ],"sentAt":"${Instant .now()} "}"""
121
125
writeToFile(contents.toByteArray(), file)
122
126
file.renameTo(File (directory, file.nameWithoutExtension))
127
+ os?.close()
128
+ os = null
123
129
incrementFileIndex()
124
130
}
125
131
@@ -132,10 +138,22 @@ class EventsFileManager(
132
138
// Atomic write to underlying file
133
139
// TODO make atomic
134
140
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
+ })
139
157
}
140
158
}
141
159
You can’t perform that action at this time.
0 commit comments