Skip to content

Commit

Permalink
Improve crash consistency
Browse files Browse the repository at this point in the history
  • Loading branch information
basil committed Jan 1, 2024
1 parent 2e26745 commit e3bffdf
Showing 1 changed file with 17 additions and 0 deletions.
17 changes: 17 additions & 0 deletions core/src/main/java/hudson/util/FileChannelWriter.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import java.nio.file.OpenOption;
import java.nio.file.Path;
import java.util.logging.Logger;
import jenkins.util.SystemProperties;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;

Expand All @@ -29,11 +30,16 @@
@Restricted(NoExternalUse.class)
public class FileChannelWriter extends Writer implements Channel {

private static final boolean REQUIRES_DIR_FSYNC =
SystemProperties.getBoolean(FileChannelWriter.class.getName() + ".requiresDirFsync", true);

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

private final Charset charset;
private final FileChannel channel;

private final Path parent;

/**
* {@link FileChannel#force(boolean)} is a <strong>very</strong> costly operation. This flag has been introduced mostly to
* accommodate Jenkins' previous behaviour, when using a simple {@link java.io.BufferedWriter}.
Expand Down Expand Up @@ -64,6 +70,7 @@ public class FileChannelWriter extends Writer implements Channel {
this.forceOnFlush = forceOnFlush;
this.forceOnClose = forceOnClose;
channel = FileChannel.open(filePath, options);
parent = filePath.getParent();
}

@Override
Expand All @@ -78,6 +85,11 @@ public void flush() throws IOException {
if (forceOnFlush) {
LOGGER.finest("Flush is forced");
channel.force(true);
if (REQUIRES_DIR_FSYNC) {
try (FileChannel parentChannel = FileChannel.open(parent)) {
parentChannel.force(true);
}
}
} else {
LOGGER.finest("Force disabled on flush(), no-op");
}
Expand All @@ -93,6 +105,11 @@ public void close() throws IOException {
if (channel.isOpen()) {
if (forceOnClose) {
channel.force(true);
if (REQUIRES_DIR_FSYNC) {
try (FileChannel parentChannel = FileChannel.open(parent)) {
parentChannel.force(true);
}
}
}
channel.close();
}
Expand Down

0 comments on commit e3bffdf

Please sign in to comment.