我有一个由多个线程访问的通用方法,
public void m(String fileName)
{
FileOutputStream fos= new FileOutputStream(fileName);
FileChannel fc = fos.getChannel();
fc.tryLock();
....
有时,两个或多个线程中的文件名可能相同,并且当我使用 tryLock() 或 lock() 时会出现异常。我如何知道锁是否已被获取?
更新:
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;
class A implements Runnable{
@Override
public void run()
{
try
{
FileOutputStream fos= new FileOutputStream("file.2txt");
FileChannel fc = fos.getChannel();
fc.tryLock();
Thread.sleep(4000);
fc.close();
System.out.println("done");
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
public class Test
{
public static void main(String[] args) throws Exception
{
new Thread(new A()).start();
Thread.sleep(2000);
new Thread(new A()).start();
}
}
我遇到异常:
java.nio.channels.OverlappingFileLockException
at sun.nio.ch.FileChannelImpl$SharedFileLockTable.checkList(Unknown Source)
at sun.nio.ch.FileChannelImpl$SharedFileLockTable.add(Unknown Source)
at sun.nio.ch.FileChannelImpl.tryLock(Unknown Source)
at java.nio.channels.FileChannel.tryLock(Unknown Source)
at run.A.run(Test.java:14)
at java.lang.Thread.run(Unknown Source)
最佳答案
How can I know if a lock has already been acquired?
最好的答案是使用fc.tryLock();
。但是,它不应该抛出异常。如果无法获取锁,它将返回null
。这是查看锁是否未锁定的最佳方法。
引用javadocs for FileChannel.tryLock() :
This method does not block. An invocation always returns immediately, either having acquired a lock on the requested region or having failed to do so. If it fails to acquire a lock because an overlapping lock is held by another program then it returns null. If it fails to acquire a lock for any other reason then an appropriate exception is thrown.
关于java - 如何知道锁已被获取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17091366/