我正在用Java创建一个应用程序,对于该应用程序我只希望运行一个实例。为此,我创建了一个文件,并在我的应用程序运行时锁定了它。
我有以下代码可在Windows上运行,但在Linux上无法运行:一旦我获得了一个锁而没有将其解锁,则可以再获得一个锁。
import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.channels.FileChannel; import java.nio.channels.FileLock; public class MyApp { private static File f; private static FileChannel channel; private static FileLock lock; public static void main(String[] args) { try { f = new File("RingOnRequest.lock"); // Check if the lock exist if (f.exists()) { // if exist try to delete it f.delete(); } // Try to get the lock channel = new RandomAccessFile(f, "rw").getChannel(); lock = channel.tryLock(); if(lock == null) { // File is lock by other application channel.close(); throw new RuntimeException("Only 1 instance of MyApp can run."); } // Add shutdown hook to release lock when application shutdown ShutdownHook shutdownHook = new ShutdownHook(); Runtime.getRuntime().addShutdownHook(shutdownHook); //Your application tasks here.. System.out.println("Running"); try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } } catch(IOException e) { throw new RuntimeException("Could not start process.", e); } } public static void unlockFile() { // release and delete file lock try { if(lock != null) { lock.release(); channel.close(); f.delete(); } } catch(IOException e) { e.printStackTrace(); } } static class ShutdownHook extends Thread { public void run() { unlockFile(); } } }
我使用了与您相同的示例,并且在Mac OS X上遇到了同样的问题。似乎文件锁定不能防止在POSIX系统上删除文件。在解锁之前,您的应用仍会对该文件具有某种处理方式。因此,请考虑使用名称为PID的锁定文件(或内部文件)。