我有一个由多个线程访问的通用方法,
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)