Java使用FileLock实现Java进程互斥锁

原理:
JDK的nio包中FileLock实现类似Linux fcntl的文件锁, 可使文件被进程互斥访问.  借助此功能, 可以实现强大的Java进程互斥锁, 从而在应用层面保证同一时间只有惟一的Jar应用进程在运行! 避免某些因素导致jar重复执行, 多个进程产生竞争,破坏业务数据. (当然, 你可以借助类似ubuntu的upstart脚本或者ps -p <pid>之类的做法来做到相同的功能).
实现:

  1. package test;
  2. import java.io.File;
  3. import java.io.IOException;
  4. import java.io.RandomAccessFile;
  5. import java.nio.channels.FileChannel;
  6. import java.nio.channels.FileLock;
  7. import java.util.concurrent.Callable;
  8. import java.util.concurrent.TimeUnit;
  9. public class FileLockTest {
  10.         public static void main(String[] args) throws Exception {
  11.                 exclusiveWithFileLock(new Callable<Void>() {
  12.                         @Override
  13.                         public Void call() throws Exception {
  14.                                 TimeUnit.SECONDS.sleep(10); // 使用休眠模拟业务逻辑
  15.                                 return null;
  16.                         }
  17.                 });
  18.         }
  19.         public static <V> V exclusiveWithFileLock(Callable<V> caller)
  20.                         throws Exception {
  21.                 File lockFile = new File("/tmp/"+FileLockTest.class.getCanonicalName());//使用类名做为文件名称
  22.                 if (!lockFile.exists()) {
  23.                         if (!lockFile.getParentFile().exists()) {
  24.                                 lockFile.getParentFile().mkdirs();
  25.                         }
  26.                         if (!lockFile.createNewFile()) {
  27.                                 throw new IOException("create lock file failed! ");
  28.                         }
  29.                 }
  30.                 FileChannel fc = null;
  31.                 try {
  32.                         fc = new RandomAccessFile(lockFile,"rw").getChannel();
  33.                         FileLock lck = fc.tryLock();
  34.                         if (lck == null) {
  35.                                 System.out.println("File is lock by another programme");
  36.                                 System.exit(1);
  37.                         } else {
  38.                                 System.out.println("Do your work here...");
  39.                                 return caller.call();
  40.                         }
  41.                 } finally {
  42.                         if (fc != null) {
  43.                                 fc.close();
  44.                         }
  45.                 }
  46.                 return null;
  47.         }
  48. }

复制代码

结果:

  1. xuser@pc120:~/myworkspace/source/jademo/src$ java test.FileLockTest
  2. File is lock by another programme
  3. xuser@pc120:~/myworkspace/source/jademo/src$ java test.FileLockTest
  4. Do your work here...

复制代码

优势:
1. 实现简单, 功能强大.

posted @ 2016-09-07 13:58  HEZOF  阅读(659)  评论(0编辑  收藏  举报