Skip to content

Instantly share code, notes, and snippets.

@tomwhoiscontrary
Last active December 18, 2017 11:20
Show Gist options
  • Save tomwhoiscontrary/3555d179aa66bbee6026c647ea8737da to your computer and use it in GitHub Desktop.
Save tomwhoiscontrary/3555d179aa66bbee6026c647ea8737da to your computer and use it in GitHub Desktop.
A fun demo of unexpected (to me) file timestamp behaviour on Linux
import java.io.IOException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.time.Instant;
/**
* Run this program, then kill -9 it. Then stat and cat the file it writes to, and compare the file's modification
* timestamp to the timestamp written to the file.
* <p>
* Note that this code never flushes the file, but because it is memory-mapped, the kernel will flush it after the
* process dies.
*/
public class Stamper {
public static void main(String[] args) throws IOException {
Path path = Files.createTempFile(Paths.get(System.getProperty("user.home")), Stamper.class.getSimpleName(), ".txt");
System.out.println(path);
FileChannel fileChannel = FileChannel.open(path, StandardOpenOption.READ, StandardOpenOption.WRITE);
int timestampLength = Instant.now().toString().length();
MappedByteBuffer buffer = fileChannel.map(FileChannel.MapMode.READ_WRITE, 0, timestampLength + 1);
buffer.put(timestampLength, (byte) '\n');
while (true) {
buffer.clear();
buffer.put(Instant.now().toString().getBytes());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment