欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java编程实现排他锁代码详解

程序员文章站 2024-02-23 19:06:22
一 .前言 某年某月某天,同事说需要一个文件排他锁功能,需求如下: (1)写操作是排他属性 (2)适用于同一进程的多线程/也适用于多进程的排他操作 (3)容...

一 .前言

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

(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 totalcost = (tsend - tsbegin); 
      if(totalcost < locktime){ 
        thread.sleep(locktime - totalcost); 
      } 
    } 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(), false, 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。

在经过一段曲折寻找真理的道路后,终于在*上找到一个帖子 ,指明了 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, within a program, 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语言中cas指令的无锁编程实现实例以及本站其他相关专题,希望对大家有所帮助。如有不足之处,欢迎留言指出,小编一定及时更正,给大家提供更好的阅读环境和帮助,感谢朋友们对本站的支持