简体   繁体   English

在Java中,访问RandomAccessFile时从FileChannel获取FileLock的保证方法是什么?

[英]In Java What is the guaranteed way to get a FileLock from FileChannel while accessing a RandomAccessFile?

I am trying to use 我正在尝试使用

FileLock lock(long position, long size,boolean shared)

in FileChannel object As per the javadoc it can throw OverlappingFileLockException . FileChannel对象中,根据javadoc,它可以引发OverlappingFileLockException When I create a test program with 2 threads lock method seems to be waiting to acquire the lock (both exclusive and non exclusive) But when the number threads increases in the acutal scenario over lapping file lock exception is thrown and processing slows down due the block at File lock table. 当我创建具有2个线程的测试程序时,锁定方法似乎正在等待获取锁定(排他和非排他),但是在实际情况下,线程数量增加,而重叠文件则抛出异常,并且由于该块而导致处理速度变慢在文件锁定表中。

What is the best way to acquire lock avoiding the OverlappingFileLockException ? 避免OverlappingFileLockException的获取锁的最佳方法是什么?

Avoid letting your regions overlap. 避免让您的区域重叠。 You could also try to set the shared flag to true . 您也可以尝试将shared标志设置为true But beware, that shared locks are os dependent. 但是请注意,共享锁取决于操作系统。 So they may not be available on all systems. 因此,它们可能并非在所有系统上都可用。

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

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