我正在尝试实现跨进程锁定,我只想要一个 jvm 来运行我的一段代码。以下代码在任何情况下都会中断吗?如果是这样如何使它牢不可破?
PS:以下代码取自这里并根据我的要求进行了修改。
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();
}
});
}
}