简体   繁体   English

Java中的进程间文件锁定

[英]Inter-process file locking in Java

I haven't found anything specific, only threads like that , which doesn't show the implementation. 我还没有发现任何特定的东西,只有类似那的线程,没有显示实现。

I need to create a file lock shared between two or more processes(not threads!). 我需要创建两个或多个进程(不是线程!)之间共享的文件锁。 I need to read/write in a file in one process and guarantee that no other process writes to the file in the same time. 我需要在一个进程中读取/写入文件,并确保没有其他进程同时写入该文件。 FileChannel.lock() doesn't do the job, because it throws an exception(OverlappingFileLockException) whenever the lock exists. FileChannel.lock()不会执行此操作,因为只要存在锁,它都会引发异常(OverlappingFileLockException)。

I have two ideas how to achieve a inter-process mutex, but both seems a little bit bad to me. 我有两个想法如何实现进程间互斥,但对我来说似乎都有些不好。

  1. Repeat locking action until it works - quite disgusting, but simple and it should work I guess? 重复执行锁定操作直到它起作用-相当令人讨厌,但是简单,它应该可以工作吗?

     RandomAccessFile rFile = new RandomAccessFile(file, "rw"); FileChannel channel = rFile.getChannel(); FileLock lock; boolean locked = false; while(!locked) { try { lock = channel.lock(); locked = true; } catch(OverlappingFileLockException e) { Thread.sleep(10); } } lock.release(); 
  2. Whenever the exception is thrown, transform the current process into a server. 每当引发异常时,就将当前进程转换为服务器。 Use ServerSocket to listen to other processes and Socket to communicate that lock.release() has been called. 使用ServerSocket侦听其他进程,并使用Socket传达已调用lock.release()的信息。 This one sounds like using a cannon to kill a fly to me. 这听起来像是用大炮杀死了我的苍蝇。

Is any of these 2 correct way of handling my problem? 这两种解决我的问题的正确方法中的任何一种吗? Or is there an already existing Java mechanism that allows locking a file across processes? 还是已有一个Java机制允许跨进程锁定文件?

try (RandomAccessFile raf = new RandomAccessFile(file, "rw")) {
    while (raf.getChannel().tryLock() == null) {
        Thread.sleep(10);
    }
    // lock acquired
}

The lock will be automatically released (indirectly - via closing the RandomAccessFile ) by the try-with-resurces block. try-with-resurces块将自动释放锁定(间接地-通过关闭RandomAccessFile )。
BTW the OverlappingFileLockException is thrown because the current JVM already has the lock, or a thread of the current JVM is already waiting for it. 顺便说一句,因为当前JVM已经具有锁,或者当前JVM的线程已经在等待锁,所以抛出OverlappingFileLockException

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

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