Skip to content

Commit

Permalink
Better atomic config saving
Browse files Browse the repository at this point in the history
Pass the `ATOMIC_MOVE` flag to signal that we want the final file renaming to
be atomic if possible. Catch the exception that occurs when it's not supported
on the OS or drive, and fall back to not using that flag.
  • Loading branch information
garfieldnate committed Jan 8, 2025
1 parent d3ce90c commit e474888
Showing 1 changed file with 14 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,14 @@
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.nio.file.AtomicMoveNotSupportedException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.logging.Logger;

import static java.nio.file.StandardCopyOption.ATOMIC_MOVE;
import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;

public class AppProperties extends java.util.Properties
{
Expand All @@ -27,6 +31,8 @@ public class AppProperties extends java.util.Properties

protected final String kVersion = "Version";

private static final Logger LOGGER = Logger.getLogger(AppProperties.class.getName());

/**
* The filename is just a filename--not a full path. The file is stored
* relative to the user's home directory on Unix or the user's application
Expand Down Expand Up @@ -146,7 +152,6 @@ public boolean Load(String version) throws java.io.IOException
// File doesn't exist. No properties to load, so we're done.
return false;
}

}

public void Save() throws java.io.IOException {
Expand All @@ -162,8 +167,13 @@ public void Save() throws java.io.IOException {
try (FileOutputStream output = new FileOutputStream(tempPath.toFile())) {
this.store(output, this.m_Header);
}

Files.move(tempPath, finalPath, StandardCopyOption.REPLACE_EXISTING);
try {
Files.move(tempPath, finalPath, REPLACE_EXISTING, ATOMIC_MOVE);
} catch (AtomicMoveNotSupportedException e) {
LOGGER.warning(
"Cannot write " + finalPath + " atomically (" + e.getMessage() + "); falling back to non-atomic write");
Files.move(tempPath, finalPath, REPLACE_EXISTING);
}
}

public String getFilename()
Expand Down

0 comments on commit e474888

Please sign in to comment.