Java   发布时间:2019-10-05  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了Java编程实现排他锁代码详解大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

一 .前言

某年某月某天,同事说需要一个文件排他锁功能,需求如下:

(1)写操作是排他属性
(2)适用于同一进程的多线程/也适用于多进程的排他操作
(3)容错性:获得锁的进程若Crash,不影响到后续进程的正常获取锁

二 .解决方案

1. 最初的构想

在Java领域,同进程的多线程排他实现还是较简易的。比如使用线程同步变量标示是否已锁状态便可。但不同进程的排他实现就比较繁琐。使用已有API,自然想到 java.nio.chAnnels.FileLock:如下

/** 
   * @param file 
   * @param strToWrite 
   * @param append 
   * @param lockTime 以毫秒为单位,该值只是方便模拟排他锁时使用,-1表示不虑该字段 
   * @return 
   */ 
  public static Boolean lockAndWrite(File file,String strToWrite,Boolean append,int lockTimE){ 
    if(!file.exists()){ 
      return false; 
    } 
    RandomAccessFile fis = null; 
    FileChAnnel fileChAnnel = null; 
    FileLock fl = null; 
    long tsBegin = System.currentTimeMillis(); 
    try { 
      fis = new RandomAccessFile(file,"rw"); 
      fileChAnnel = fis.getChAnnel(); 
      fl = fileChAnnel.tryLock(); 
      if(fl == null || !fl.isValid()){ 
        return false; 
      } 
      log.info("threadId = {} lock success",Thread.currentThread()); 
      // if append 
      if(append){ 
        long length = fis.length(); 
        fis.seek(length); 
        fis.writeUTF(strToWritE); 
      //if not,clear the content,then write 
      }else{ 
        fis.setLength(0); 
        fis.writeUTF(strToWritE); 
      } 
      long tsEnd = System.currentTimeMillis(); 
      long @R_601_10586@lCost = (tsEnd - tsBegin); 
      if(@R_601_10586@lCost < lockTimE){ 
        Thread.sleep(lockTime - @R_601_10586@lCost); 
      } 
    } catch (Exception E) { 
      log.error("RandomAccessFile error",E); 
      return false; 
    }finally{ 
      if(fl != null){ 
        try { 
          fl.release(); 
        } catch (IOException E) { 
          e.printStackTrace(); 
        } 
      } 
      if(fileChAnnel != null){ 
        try { 
          fileChAnnel.close(); 
        } catch (IOException E) { 
          e.printStackTrace(); 
        } 
      } 
      if(fis != null){ 
        try { 
          fis.close(); 
        } catch (IOException E) { 
          e.printStackTrace(); 
        } 
      } 
    } 
    return true; 
  } 

一切看起来都是那么美好,似乎无懈可击。于是加上两种测试场景代码:

(1)同一进程,两个线程同时争夺锁,暂定命名为测试程序A,期待结果:有一线程获取锁失败
(2)执行两个进程,也就是执行两个测试程序A,期待结果:有一进程某线程获得锁,另一线程获取锁失败

public static void main(String[] args) { 
    new Thread("write-thread-1-lock"){ 
      @Override 
      public void run() { 
        FileLockUtils.lockAndWrite(new File("/data/Hello.txt"),"write-thread-1-lock" + System.currentTimeMillis(),false,30 * 1000);} 
    }.start(); 
    new Thread("write-thread-2-lock"){ 
      @Override 
      public void run() { 
        FileLockUtils.lockAndWrite(new File("/data/Hello.txt"),"write-thread-2-lock" + System.currentTimeMillis(),30 * 1000); 
      } 
    }.start(); 
  } 

2.世界不像你想的那样

上面的测试代码在单个进程内可以达到我们的期待。但是同时运行两个进程,在Mac环境(java8) 第二个进程也能正常获取到锁,在Win7(java7)第二个进程则不能获取到锁。为什么?难道TryLock不是排他的?

其实不是TryLock不是排他,而是chAnnel.close 的问题,官方说法:

On some systems,closing a chAnnel releases all locks Held by the Java virtual machine on the 
 underlying file regardless of whether the locks were acquired via that chAnnel or via  
another chAnnel open on the same file.it is strongly recommended that,within a program,a unique 
 chAnnel be used to acquire all locks on any given file. 

原因就是在某些操作系统,close某个chAnnel将会导致JVM释放所有lock。也就是说明了上面的第二个测试用例为什么会失败,因为第一个进程的第二个线程获取锁失败后,我们调用了chAnnel.close ,所有将会导致释放所有lock,所有第二个进程将成功获取到lock。

在经过一段曲折寻找真理的道路后,终于在stackoverflow上找到一个帖子 ,指明了 lucence 的 NativeFSLock,NativeFSLock 也是存在多个进程排他写的需求。笔者参的是lucence 4.10.4 的NativeFSLock源码,具体可见地址,具体可见obtain 方法,NativeFSLock 的设计思想如下:

(1)每一个锁,都有本地对应的文件。
(2)本地一个static类型线程安全的Set<String> LOCK_HelD维护目前所有锁的文件路径,避免多线程同时获取锁,多线程获取锁只需判断LOCK_HelD是否已有对应的文件路径,有则表示锁已被获取,否则则表示没被获取。
(3)假设LOCK_HelD 没有对应文件路径,则可对File的chAnnel TryLock。

public synchronized Boolean obtain() throws IOException { 
    if (lock != null) { 
      // Our instance is already locked: 
      return false; 
    } 
    // Ensure that lockDir exists and is a directory. 
    if (!lockDir.exists()) { 
      if (!lockDir.mkdirs()) 
        throw new IOException("CAnnot create directory: " + lockDir.getAbsolutePath()); 
    } else if (!lockDir.isDirectory()) { 
      // TODO: NoSuchDirectoryException instead? 
      throw new IOException("Found regular file where directory expected: " + lockDir.getAbsolutePath()); 
    } 
    final String canonicalPath = path.getCanonicalPath(); 
    // Make sure nobody else in-process has this lock Held 
    // already,and,mark it Held if not: 
    // This is a pretty crazy workaround for some documented 
    // but yet awkWARD JVM behavior: 
    // 
    // On some systems,closing a chAnnel releases all locks Held by the 
    // Java virtual machine on the underlying file 
    // regardless of whether the locks were acquired via that chAnnel or via 
    // another chAnnel open on the same file. 
    // it is strongly recommended that,a unique chAnnel 
    // be used to acquire all locks on any given 
    // file. 
    // 
    // This essentially means if we close "A" chAnnel for a given file all 
    // locks might be released... the odd part 
    // is that we can't re-obtain the lock in the same JVM but from a 
    // different process if that happens. NevertHeless 
    // this is super trappy. See LUCENE-5738 
    Boolean obtained = false; 
    if (LOCK_HelD.add(canonicalPath)) { 
      try { 
        chAnnel = FileChAnnel.open(path.toPath(),StandardopenOption.CREATE,StandardopenOption.WRITE); 
        try { 
          lock = chAnnel.tryLock(); 
          obtained = lock != null; 
        } catch (IOException | OverlappingFileLockException E) { 
          // at least on OS X,we will sometimes get an 
          // intermittent "Permission Denied" IOException,// which seems to simply mean "you failed to get 
          // the lock". But other IOExceptions could be 
          // "peRMANent" (eg,locking is not supported via 
          // the filesystem). So,we record the failure 
          // reason here; the timeout obtain (usually the 
          // one calling us) will use this as "root cause" 
          // if it fails to get the lock. 
          failureReason = e; 
        } 
      } finally { 
        if (obtained == falsE) { // not successful - clear up and move 
                      // out 
          clearLockHeld(path); 
          final FileChAnnel toClose = chAnnel; 
          chAnnel = null; 
          closeWhileHandlingException(toClosE); 
        } 
      } 
    } 
    return obtained; 
  } 

总结

以上就是本文关于Java编程实现排他锁代码详解的全部内容,感兴趣的朋友可以参阅:Java并发编程之重入锁与读写锁详解java中的互斥锁信号量和多线程等待机制Java语言中cas指令的无锁编程实现实例以及本站其他相关专题,希望对大家有所帮助。如有不足之处,欢迎留言指出,小编一定及时更正,给大家提供更好的阅读环境和帮助,感谢朋友们对本站的支持

大佬总结

以上是大佬教程为你收集整理的Java编程实现排他锁代码详解全部内容,希望文章能够帮你解决Java编程实现排他锁代码详解所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签:排他锁