Skip to content

Debloat any Android or Google TV over Wi-Fi and get an Apple TV-style home.

addons/game-day: two saves at once never trip over each other's temporary file

Justin Newmana081203d6279
diff --git a/addons/game-day/app/src/main/java/io/github/justinnewman/gameday/Repository.java b/addons/game-day/app/src/main/java/io/github/justinnewman/gameday/Repository.java
index c4cb423f7..c590e4763 100644
--- a/addons/game-day/app/src/main/java/io/github/justinnewman/gameday/Repository.java
+++ b/addons/game-day/app/src/main/java/io/github/justinnewman/gameday/Repository.java
@@ -270,10 +270,22 @@ final class Repository {
}
}
- /** Write to a temporary file, then move it into place, so a reader never sees half a file. */
+ private static final Object WRITING = new Object();
+
+ /**
+ * Write to a temporary file of its own, then move it into place, so a reader never sees half a file. One write at
+ * a time: the TV's settings and the setup script can both save the list.
+ */
static void write(File f, String text) {
- File tmp = new File(f.getParentFile(), f.getName() + ".tmp");
+ synchronized (WRITING) {
+ writeNow(f, text);
+ }
+ }
+
+ private static void writeNow(File f, String text) {
+ File tmp = null;
try {
+ tmp = Files.createTempFile(f.getParentFile().toPath(), f.getName() + ".", ".part").toFile();
Files.write(tmp.toPath(), text.getBytes(StandardCharsets.UTF_8));
try {
Files.move(tmp.toPath(), f.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
@@ -282,6 +294,9 @@ final class Repository {
}
} catch (IOException e) {
throw new IllegalStateException("could not save " + f.getName(), e);
+ } finally {
+ //noinspection ResultOfMethodCallIgnored
+ if (tmp != null && tmp.exists()) tmp.delete();
}
}
}
diff --git a/addons/game-day/app/src/test/java/io/github/justinnewman/gameday/RepositoryTest.java b/addons/game-day/app/src/test/java/io/github/justinnewman/gameday/RepositoryTest.java
index 9a1333c6b..dc53ba867 100644
--- a/addons/game-day/app/src/test/java/io/github/justinnewman/gameday/RepositoryTest.java
+++ b/addons/game-day/app/src/test/java/io/github/justinnewman/gameday/RepositoryTest.java
@@ -137,6 +137,13 @@ public class RepositoryTest {
assertEquals(null, repo.status(royals.id));
}
+ @Test public void aSaveNeverTripsOverAnotherSavesTemporaryFile() throws Exception {
+ // Another save of the same file is half done: its temporary file is in the way.
+ assertTrue(new File(dir, "calendars.json.tmp").mkdir());
+ repo.save(Arrays.asList(cal("Minnesota Wild", "Hockey", 16)));
+ assertEquals(1, repo.calendars().size());
+ }
+
@Test public void dueCalendars() {
Calendar wild = cal("Minnesota Wild", "Hockey", 16);
Calendar royals = cal("Utah Royals", "Soccer", 14);