有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

多线程在java中实现跨进程锁定

我试图实现跨进程锁定,我只需要一个jvm来运行我的代码。以下代码在任何情况下都会中断吗?如果是这样的话,如何让它牢不可破

PS:以下代码取自here,并根据我的要求对其进行了修改

public class TestMe
{
    public static void main(String args[]) throws InterruptedException
    {
        try
        {
            if (crossProcessLockAcquire())
            {
                // Success - This process now has the lock. 
                System.out.println("I am invincible");
                Thread.sleep(10000);
            }
            else
            {
                System.out.println("I am doomed");
            }
        }
        finally
        {
            crossProcessLockRelease(); // try/finally is very important.
        }
    }
    private static boolean crossProcessLockAcquire()
    {
        try
        {
            file = new File(System.getProperty("java.io.tmpdir") + File.separator + "file.lock");
            if (!file.exists())
            {
                file.createNewFile();
            }
            RandomAccessFile randomAccessFile = new RandomAccessFile(file,
                    "rw");
            FileChannel fileChannel = randomAccessFile.getChannel();
            fileLock = fileChannel.tryLock();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return fileLock == null ? false : true;
    }
    private static void crossProcessLockRelease()
    {
        if (fileLock != null)
        {
            try
            {
                fileLock.release();
                fileLock = null;
                if (file.exists())
                {
                    file.delete();
                }
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }
    private static FileLock fileLock = null;
    private static File file = null;
    static
    {
        Runtime.getRuntime().addShutdownHook(new Thread()
        {
            public void run()
            {
                crossProcessLockRelease();
            }
        });
    }
}

共 (1) 个答案

  1. # 1 楼答案

    它可以在这里破裂:

            file = new File(System.getProperty("java.io.tmpdir") + File.separator + "file.lock");
            if (!file.exists())
            {
                file.createNewFile();
            }
    

    在测试文件是否存在和创建文件之间,可能是其他进程创建了该文件

    将其替换为目录,并检查.mkdir()的返回代码(如果该目录已经存在,它将失败),因为.mkdir()在文件系统级别是原子的:

    file = new File("/path/to/sentinel");
    if (!file.mkdir())
        someoneHasLocked();
    

    当然,在“解锁”上