java new File()挂在陈旧的NFS挂载点上

时间:2019-01-15 09:19:24

标签: java nfs

在我的Java代码中,我正在读取NFS挂载的目录(代码在NFS client机器上运行)。只要NFS服务器计算机已启动并正在运行,一切都很好,但是当NFS服务器关闭(由于任何原因)时,代码会挂在任何地方,从而在创建新文件到nfs安装目录中。如果我只是卸载nfs目录,我的代码就可以正常运行,但是我不想每天手动检查此类问题,而只想在我的代码中处理这种情况

这是NFS服务器的/ etc / exports:

/var/nfs/general *(rw,insecure,all_squash,no_subtree_check)

实际的Java代码很简单:

log.info("before new");
File file = new File("/var/nfs/general");
log.info("after new");

它仅在日志文件中打印“ before new”,而永远不会到达“ after after new”

我将新文件置于Executor服务中,并按建议的超时时间进行超时,但即使2秒超时仍然挂起:

How do I call some blocking method with a timeout in Java?

  • 操作系统:两台服务器(NFS客户端和服务器)上的ubuntu服务器16.04

    Java版本:1.8_172

1 个答案:

答案 0 :(得分:0)

您可以简单地将其包装在Callable下,并使用带有超时的get()。下面是一个示例代码,如果result(此处的文件)不可用,可能会在20秒后超时!

FutureTask<File> futureFile = new  FutureTask<File>(new Callable<File>(){
    public File call() throws Exception {
        return new File(filePath);
    }
});

futureFile.get(20, TimeUnit.SECONDS);

出于测试目的,我将超时时间设置为3 ns。在这种情况下,文件肯定会超时。

public static File readTimeOut(final String filePath, int timeOutInMillis) throws InterruptedException, ExecutionException, TimeoutException {
        ExecutorService executor = Executors.newFixedThreadPool(1);
        FutureTask<File> futureFile = new FutureTask<File>(new Callable<File>() {

            public File call() throws Exception {
                System.out.println("I am called");
                return new File("/usr/mohamed");
            }
    });
    executor.execute(futureFile);
    return futureFile.get(3, TimeUnit.NANOSECONDS);
}

(将所有内容保持简单。资源未正确关闭!)但这肯定可以通过FutureTask处理。

相关问题