java - 如何知道锁已被获取

标签 java multithreading file

我有一个由多个线程访问的通用方法,

     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/

相关文章:

java - 有没有一种简单的方法可以将项目列表输入数组,比如 50-100?

java - 从 HttpServletRequest 获取 AsyncContext

c++ - 哪个在内存中更快,int 或 char?还有文件映射或 block 读取?

c - 无法正确读取数字?

c - 从用于写入的 FILE 副本中将数据读入数组

java - Groovy 依赖注入(inject)

java - 异常: Operating System error code 3

ruby - 同时下载多个文件(多线程)

java - 杀死一个挂起的线程

Python:线程只能启动一次