Video in progress

Java has no timeout for file operations. When a disk or network file system freezes, how do you protect the rest of the service?

You run blocking file IO not on request threads but in a separate bounded executor, and wait for the result on a Future with a timeout. A hung thread can't be stopped, so a pool bound and a circuit breaker limit the damage; the health check also covers the IO path.

📖 Answer

FileChannel.read has no timeout parameter, and an interrupt closes the channel (ClosedByInterruptException), but it doesn't always wake a thread hung inside a native call: on a "hard" NFS mount it can wait forever. That is, you can't cancel a frozen IO, you can only stop waiting for it.

So the design is built around "isolation", not "cancellation":

private final ExecutorService fileIo = Executors.newFixedThreadPool(8,
        Thread.ofPlatform().name("file-io-", 0).factory());

byte[] readWithTimeout(Path p) throws Exception {
    Future<byte[]> f = fileIo.submit(() -> Files.readAllBytes(p));
    try {
        return f.get(2, TimeUnit.SECONDS);
    } catch (TimeoutException e) {
        f.cancel(true);
        throw new StorageUnavailableException(p, e);
    }
}

Here the request thread is freed after 2 seconds. The file-IO thread may stay frozen, but there are only 8 of them, and if they all freeze only the file feature stops working while the rest of the API stays alive. The executor's queue also has to be bounded, otherwise tasks pile up in front of the frozen pool and eat memory.

Extra layers:

  • A circuit breaker (Resilience4j): after a few timeouts, temporarily stop trying the file path and return an error right away, so you don't fill the frozen pool with new tasks.
  • Health checks. The liveness probe should not depend on IO: killing the pod over and over doesn't help with a disk problem. Readiness can take the disk state into account.
  • Mount settings. For NFS, soft + timeo + retrans return an error instead of waiting forever on IO; this is a trade-off against data integrity, so decide it together with the infra team.
  • Metrics. The busy threads and queue length of the file-IO pool are the first signal that a freeze has started.

The main idea: everybody knows to put timeouts on network calls, but a file system, especially in the cloud, is really the network too. Treat it that way.