首页 技术 正文
技术 2022年11月6日
0 收藏 404 点赞 260 浏览 1454 个字

原理:
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. 实现简单, 功能强大.

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,990
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,504
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,348
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,132
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,765
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,843