http://jimlife.wordpress.com/2008/07/21/java-application-make-sure-only-singleone-instance-running-with-file-lock-ampampampampamp-shutdownhook/
应该说,这篇文章讲述的是启动、关闭一个程序的最佳实践或常用方案。
涉及的方面是:
1,当程序已经运行时,使用lock文件,防止有人试图再次启动该程序。
2, 程序关闭时,使用shutdown hook保证一些收尾工作被执行。
代码如下,非常非常的简单~
package test.jimmy.filelock; 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 //如果抛出IO异常,说明有其他process占用,则停止运行。 //这里不仅仅是检查lock文件是否存在,而且检查是否被占用。 //这样就避免了由于特殊原因导致lock未被删除,进而导致程序无法再次启动的问题。 f.delete(); } // Try to get the lock //这个用法没见过,学习一下 //只有通过channel才能get一个FileLock 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 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(); } } }