有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java ConcurrentExecution异常&nio。文件创建符号链接时出现NoSuchFileException

我有一个包含JSON文件的目录,需要对该目录进行迭代以获取文档dName的名称。多个JSON文件可以具有相同的dName。然后需要从名为output/dName/match的文件夹创建一个指向该JSON文件的符号链接。线程首先检查dName文件夹是否存在,如果不存在,则首先创建它们。我有以下创建符号链接的代码

protected static void copyFile(String docName, Path tFilePath) throws IOException {
    final String docFolderName = "output" + docName.substring(0, docName.lastIndexOf("."));
    final String opDir = docFolderName + "match";
    path = Paths.get(opDir);
    if (Files.notExists(path)) {
        Files.createDirectories(path);
        outputAnnotationDirs.add(path.toString());
    }
    try {
        Files.createSymbolicLink(Paths.get(opDir).resolve(tFilePath.getFileName()), tFilePath);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}


protected static void Mapper(String Dir,int numThreads) throws Exception {
    final ExecutorService executorService = Executors.newFixedThreadPool(numThreads);
    final ConcurrentLinkedQueue<Future<?>> futures = new ConcurrentLinkedQueue<Future<?>>();
    final JsonParser parser = new JsonParser();
    try {
        Files.walkFileTree(Paths.get(Dir), new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(final Path tFile, BasicFileAttributes attrs) throws IOException {
                futures.add((Future<String>) executorService.submit(new Runnable() {
                    public void run() {
                        JsonObject jsonObject = null;
                        FileReader reader = null;
                        try {
                            reader = new FileReader(tFile.toFile());
                            jsonObject = (JsonObject) parser.parse(reader);
                            JsonArray instancesArray = (JsonArray) jsonObject.get("instances");
                            String dName = instancesArray.get(0).getAsJsonObject().get("dname").toString();
                            copyFile(dName, tFile);
                        } catch (FileNotFoundException e) {
                            throw new RuntimeException(e);
                        } catch (Exception e) {
                            throw new RuntimeException(e);
                        } finally {
                            try {
                                if (reader != null)
                                    reader.close();
                            } catch (IOException e) {

                                logger.error(e);
                            }
                        }                           
                    }
                }));
                return FileVisitResult.CONTINUE;
            }

        });
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        Future<?> future;
        while ((future = futures.poll()) != null) {
            try {
                future.get();
            } catch (Exception e) {
                for (Future<?> f : futures)
                    f.cancel(true);
                if (executorService != null)
                    executorService.shutdown();
                throw new Exception(e);
            }
        }
        if (executorService != null)
            executorService.shutdown();
    }
}

但是,在创建符号链接的行上会不断发生异常

Exception in thread "main" java.lang.Exception: java.util.concurrent.ExecutionException: java.lang.RuntimeException: java.nio.file.NoSuchFileException:`

例如output/document1/match/ok.json处的异常

如果我是对的,符号链接只有在该行被执行之后才会被创建。那么为什么会出现错误呢?线程创建的单个符号链接为什么会导致concurrent.ExecutionException


共 (4) 个答案

  1. # 1 楼答案

    在我看来,似乎没有任何文件异常告诉你问题出在哪里。要创建指向文件的符号链接,文件应该存在

  2. # 2 楼答案

    正如我在评论中所说:

     path = Paths.get(opDir); 
    

    这是一种比赛条件

  3. # 3 楼答案

    简单。。这是一个比赛条件。将相对路径变量的范围更改为局部变量

  4. # 4 楼答案

    Then why does the error occur?

    发生此错误的原因是"parent directory creation"在创建符号链接之前没有创建所有父目录。例如:如果您有"dname": "a/b/c/somedname1.txt"的json条目,那么a/b/c文件夹似乎不会被创建。这就是NoSuchFileException被抛出的原因。现在,您已经有了创建目录的逻辑,但为什么不起作用呢?如果你在一个线程中运行的话,它会运行得很好。为什么不在多线程中

    因为path变量在所有线程之间共享,并且同时被许多线程修改

    path = Paths.get(opDir);
    if (Files.notExists(path)) {
        Files.createDirectories(path);
        outputAnnotationDirs.add(path.toString());
    }
    

    当在多个线程中运行时,比如说,一个线程有dname:a/b/c/dname1.txt,另一个线程有dname:e/f/g/dname2.txt。第一个线程可能最终创建e/f/g而不是a/b/c目录。经典的并发问题。将path作为局部变量将立即解决您的问题。或者在单个线程中运行进程

    1. 如果您的原始文件被另一个进程删除,您将得到一个java.io.FileNotFoundException
    2. 如果你的符号链接已经存在,你会得到一个java.nio.file.FileAlreadyExistsException
    3. java.nio.file.NoSuchFileException当您无法对文件执行操作(如删除)时发生。或者在父文件夹不存在时尝试创建文件/符号链接

    And individual Symbolic Link creation by a thread why does it cause concurrent.ExecutionException?

    当你在future上做getNoSuchFileException被你的RunTimeException包裹ExecutionException。因为RunTimeException发生在另一个线程上,而下面的调用发生在主线程上。所以Executor包装异常,并在从主线程调用的下面调用时激发

    future.get();
    

    谢谢