From 30afab690e2727c59121e062bf5a256207f55615 Mon Sep 17 00:00:00 2001 From: Hai Zhang Date: Wed, 20 May 2020 12:07:11 -0700 Subject: [PATCH] Properly keep compatibility with openRead() during a write. Bug: 157092639 Test: atest AppIdleHistoryTests#testFilesCreation Change-Id: I7d6808139aa41b25715293207b8ad42f9f42ef65 --- core/java/android/util/AtomicFile.java | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/core/java/android/util/AtomicFile.java b/core/java/android/util/AtomicFile.java index 1dd4cbb403db4..7ede6531899c4 100644 --- a/core/java/android/util/AtomicFile.java +++ b/core/java/android/util/AtomicFile.java @@ -227,8 +227,18 @@ public class AtomicFile { } } - // Don't delete mNewName here - it was okay to call openRead() between startWrite() and - // finishWrite(), and we have to keep supporting it. + // It was okay to call openRead() between startWrite() and finishWrite() for the first time + // (because there is no backup file), where openRead() would open the file being written, + // which makes no sense, but finishWrite() would still persist the write properly. For all + // subsequent writes, if openRead() was called in between, it would see a backup file and + // delete the file being written, the same behavior as our new implementation. So we only + // need a special case for the first write, and don't delete the new file in this case so + // that finishWrite() can still work. + if (mNewName.exists() && mBaseName.exists()) { + if (!mNewName.delete()) { + Log.e(LOG_TAG, "Failed to delete outdated new file " + mNewName); + } + } return new FileInputStream(mBaseName); }