gpt4 book ai didi

java - java中跨进程锁的实现

转载 作者:行者123 更新时间:2023-11-30 04:32:39 25 4
gpt4 key购买 nike

我正在尝试实现跨进程锁定,我只想要一个 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();
}
});
}
}

最佳答案

它可能会在这里中断:

        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();

当然,“解锁”时的.delete()

关于java - java中跨进程锁的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14278991/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com