简体   繁体   English

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

[英]java new File() hangs on stale NFS mount point

In my java code i'm reading a NFS mounted directory (code runs on NFS client machine). 在我的java代码中,我正在读取NFS安装目录(代码在NFS client机器上运行)。 Everything's fine as long as NFS server machine is up and running but when the NFS server is down (for any reason), the code hangs anywhere that creating new File to nfs mounted directory. 只要NFS服务器机器启动并运行,但是当NFS服务器关闭时(由于任何原因),代码会挂起,无论在创建新文件到nfs安装目录的任何地方,代码都会挂起。 If i simply umount the nfs directory, my code runs with no problem, but i don't want to manually check for such a problems every day and wanted to handle this scenario only in my code 如果我只是卸载nfs目录,我的代码运行没有问题,但我不想每天手动检查这样的问题,只想在我的代码中处理这种情况

this is /etc/exports of NFS Server: 这是NFS服务器的/ etc / exports:

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

The actual java code is simply: 实际的java代码很简单:

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

It only prints "before new" in log file and never reaches the "after new" 它只在日志文件中打印“before new”并且永远不会到达“after new”之后

I put the new File in Executor service with timeout like what this suggested but still hangs even with 2 seconds timeout: 我把新文件放在Executor服务中,超时就像这个建议,但是即使2秒超时也会挂起:

How do I call some blocking method with a timeout in Java? 如何在Java中使用超时调用某些阻塞方法?

  • OS: ubuntu server 16.04 on both servers (NFS client and server) 操作系统:两台服务器上的ubuntu服务器16.04(NFS客户端和服务器)

    Java version: 1.8_172 Java版本:1.8_172

You can simply wrap it under a Callable and use get() with a timeout. 您可以将其简单地包装在Callable下,并使用带超时的get()。 Below is a sample code which can timeout after 20 seconds if result(File here) is not available! 下面是一个示例代码,如果结果(此处为文件)不可用,则可在20秒后超时!

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

futureFile.get(20, TimeUnit.SECONDS);

I've made the timeout to 3 ns for testing purpose. 为了测试目的,我将超时时间设为3 ns。 File would surely be timed-out in this case. 在这种情况下,文件肯定会超时。

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);
}

(Kept everything simple. Resources aren't closed properly!) But this can surely be handled with FutureTask. (保持一切简单。资源没有正确关闭!)但这肯定可以用FutureTask处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM