繁体   English   中英

将文件/“文件夹”锁定到特定的JVM,并在锁定时进行迭代

[英]Lock file/“folder” to a specific JVM and iterate if locked

我正在使用多个JVM,但是我需要每个JVM使用特定的文件夹。 我想要做的是遍历文件夹,直到找到未锁定的文件,然后锁定它以使用该特定文件夹。

在这里,我要过滤要使用的文件夹:

  // Filter 'fran' folders
  String dir = System.getProperty("user.dir");
  FilenameFilter filter = new FilenameFilter() {
     public boolean accept(File dir, String name) {
        String lowercaseName = name.toLowerCase();
        if (lowercaseName.startsWith("fran")) {
           return true;
        } else {
           return false;
        }
     }
  };
  File[] dirs = new File(dir).listFiles(filter);

然后,我尝试浏览文件夹,并使用f.canWrite()检查它是否被锁定。 但是,它似乎总是只使用一个文件夹,而忽略其他文件夹。

  // Find available folder
  boolean lock = true;
  String lock_folder = "";
  FileChannel fileChannel = null;
  FileLock lockfile = null;
  File f = null;

  while (lock) {
     for (File folder : dirs) {
        f = new File(folder + "\\lock.txt");
        Boolean isnotlocked = f.canWrite();
        if (isnotlocked) {
           fileChannel = new RandomAccessFile(f, "rw").getChannel();
           lockfile = fileChannel.lock();
           lock = false;
           lock_folder = folder.getAbsolutePath();
           break;
        }
     }
  }

我以前尝试过在没有FileLock的情况下完成所需的工作,在特定文件夹中创建文件,然后在完成后删除。 如果该文件夹没有该文件,它将创建并锁定该JVM。 但是我认为JVM混合起来会导致结果不好。

希望你能理解我的问题,希望能有所帮助。

这里有一些想法:

假设一个流程类CustomProcess.java 这在单独的线程中运行。 该类具有一个构造函数,该构造函数将文件夹作为参数。 假设filePath1是文件夹的路径,并且已从FileChooser接受。

(a)应用程序如何工作:

将选定的文件夹filePath1放入List<File>List<Path>类的集合中-称为processFilesList 这由所有进程共享(也许是static成员)(这需要是java.util.concurrent包中的并发集合)。 此列表跟踪已被处理的文件夹。 在过程开始之前,检查filePath1是否已在processFilesList

(b)创建并开始该过程:

CustomProcess p1 = new CustomProcess(filePath1);
p1.startProcess(); // here the application does whatever with the files in the folder.


选项2

将所有需要处理的文件夹文件路径放入Queue集合中。 一次或通过多个进程处理每个文件夹(及其所需的文件)。 队列可以是先进先出(FIFO)或后进先出(LIFO)。 可以根据以下要求考虑这些并发队列实现: ConcurrentLinkedQueueLinkedBlockingQueueConcurrentLinkedDequeLinkedBlockingDeque

暂无
暂无

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

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