java - 进程无法访问该文件,因为它正被另一个进程使用

2022-09-02 10:56:54

我有一段代码来监视目录以添加文件。每当将新文件添加到目录中时,都会选取该文件的内容并将其发布在 kafka 上,然后删除该文件。

当我发出单个请求时,这有效,但是一旦我将代码提交给jMeter的5或10个用户请求,内容就会成功发布在kafka上,但代码无法删除文件。我收到一条消息..FileSystemExceptionThe process cannot access the file because it is being used by another process.

我想有一些并发问题,我无法看到。

public void monitor() throws IOException, InterruptedException {
    Path faxFolder = Paths.get(TEMP_FILE_LOCATION);
    WatchService watchService = FileSystems.getDefault().newWatchService();
    faxFolder.register(watchService, StandardWatchEventKinds.ENTRY_CREATE);
    boolean valid = true;
    do {
        WatchKey watchKey = watchService.take();
        for (WatchEvent<?> event : watchKey.pollEvents()) {
            if (StandardWatchEventKinds.ENTRY_CREATE.equals(event.kind())) {
                String fileName = event.context().toString();
                publishToKafka(new File(TEMP_FILE_LOCATION + fileName).toPath(), "topic");
            }
        }
        valid = watchKey.reset();
    } while (valid);
}

private void publishToKafka(Path path, String topic) {
    try (BufferedReader reader = Files.newBufferedReader(path)) {
        String input = null;
        while ((input = reader.readLine()) != null) {
            kafkaProducer.publishMessageOnTopic(input, topic);
        }
    } catch (IOException e) {
        LOG.error("Could not read buffered file to send message on kafka.", e);
    } finally {
        try {
            Files.deleteIfExists(path); // This is where I get the exception
        } catch (IOException e) {
            LOG.error("Problem in deleting the buffered file {}.", path.getFileName(), e);
        }
    }
}

异常日志 :

java.nio.file.FileSystemException: D:\upload\notif-1479974962595.csv: The process cannot access the file because it is being used by another process.

    at sun.nio.fs.WindowsException.translateToIOException(Unknown Source)
    at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
    at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
    at sun.nio.fs.WindowsFileSystemProvider.implDelete(Unknown Source)
    at sun.nio.fs.AbstractFileSystemProvider.deleteIfExists(Unknown Source)
    at java.nio.file.Files.deleteIfExists(Unknown Source)
    at com.panasonic.mdw.core.utils.MonitorDirectory$FileContentPublisher.publishToKafka(MonitorDirectory.java:193)
    at com.panasonic.mdw.core.utils.MonitorDirectory$FileContentPublisher.sendData(MonitorDirectory.java:125)
    at com.panasonic.mdw.core.utils.MonitorDirectory$FileContentPublisher.run(MonitorDirectory.java:113)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

答案 1

查看您的代码,似乎当一个文件被线程再次选取以进行发布时,另一个线程正在选取该文件进行发布。这就是为什么没有人能够删除它。它必须只是并发问题。您应该根据标准重新设计代码:可以同时运行的步骤和不能同时运行的步骤。所以整个过程的步骤是:

  1. 拿起一个文件(主线程应该这样做)
  2. 发布文件(调用其他线程来做)
  3. 删除文件(称为线程应将其删除)
  4. 检查是否存在任何文件(主线程也可以这样做)

此外,选择文件的那一刻,您可以将其读入缓冲区 ,删除它,然后继续发布。这将确保主线程不会将此文件分配给其他线程。


答案 2

在 WatchService 事件中添加睡眠时间始终是一个更好的主意:

if (StandardWatchEventKinds.ENTRY_CREATE.equals(event.kind())) {

       try {
            Thread.sleep(3000);
       } catch (InterruptedException e) {
            e.printStackTrace();
       }

// now do your intended jobs ... 

我需要添加睡眠时间,否则它不适用于多个请求,并用于获取错误:

The process cannot access the file because it is being used by another process