Skip to content

Commit

Permalink
Fix #973 Make sure all resources are closed
Browse files Browse the repository at this point in the history
Make sure all FileStream and FileLock are closed using AutoClose pattern.
  • Loading branch information
chkuang-g committed Jun 17, 2022
1 parent 486bb50 commit 2777b4c
Showing 1 changed file with 27 additions and 20 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -66,31 +66,38 @@ public static void writeTokenToInternalStorage(Context context, String token) {
// Write out the buffer length into the first four bytes.
sizeBuffer.order(ByteOrder.LITTLE_ENDIAN);
sizeBuffer.putInt(buffer.length);
FileLock lock = null;
try {
// Acquire lock. This prevents the C++ code from consuming and clearing the file while we
// append to it.
FileOutputStream lockFileStream = context.openFileOutput(MessageWriter.LOCK_FILE, 0);
lock = lockFileStream.getChannel().lock();

FileOutputStream outputStream =
context.openFileOutput(MessageWriter.STORAGE_FILE, Context.MODE_APPEND);
// We send both the buffer length and the buffer itself so that we can potentially process
// more than one event in the case where they get queued up.
// try (FileOutputStream lockFileStream = context.openFileOutput(MessageWriter.LOCK_FILE, 0)) {
// // Acquire lock. This prevents the C++ code from consuming and clearing the file while we
// // append to it.
// try (FileLock lock = lockFileStream.getChannel().lock()) {
// try (FileOutputStream outputStream =
// context.openFileOutput(MessageWriter.STORAGE_FILE, Context.MODE_APPEND)) {
// // We send both the buffer length and the buffer itself so that we can potentially
// // process more than one event in the case where they get queued up.
// outputStream.write(sizeBuffer.array());
// outputStream.write(buffer);
// } catch (Exception e) {
// e.printStackTrace();
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
try (FileOutputStream lockFileStream = context.openFileOutput(MessageWriter.LOCK_FILE, 0);
// Acquire lock. This prevents the C++ code from consuming and clearing the file while we
// append to it.
FileLock lock = lockFileStream.getChannel().lock();
FileOutputStream outputStream =
context.openFileOutput(MessageWriter.STORAGE_FILE, Context.MODE_APPEND)) {
// We send both the buffer length and the buffer itself so that we can potentially
// process more than one event in the case where they get queued up.
outputStream.write(sizeBuffer.array());
outputStream.write(buffer);
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
// Release the lock.
try {
if (lock != null) {
lock.release();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

Expand Down

0 comments on commit 2777b4c

Please sign in to comment.