`
deepfuture
  • 浏览: 4332376 次
  • 性别: Icon_minigender_1
  • 来自: 湛江
博客专栏
073ec2a9-85b7-3ebf-a3bb-c6361e6c6f64
SQLite源码剖析
浏览量:79402
1591c4b8-62f1-3d3e-9551-25c77465da96
WIN32汇编语言学习应用...
浏览量:68357
F5390db6-59dd-338f-ba18-4e93943ff06a
神奇的perl
浏览量:101480
Dac44363-8a80-3836-99aa-f7b7780fa6e2
lucene等搜索引擎解析...
浏览量:281131
Ec49a563-4109-3c69-9c83-8f6d068ba113
深入lucene3.5源码...
浏览量:14596
9b99bfc2-19c2-3346-9100-7f8879c731ce
VB.NET并行与分布式编...
浏览量:65547
B1db2af3-06b3-35bb-ac08-59ff2d1324b4
silverlight 5...
浏览量:31310
4a56b548-ab3d-35af-a984-e0781d142c23
算法下午茶系列
浏览量:45197
社区版块
存档分类
最新评论

java-tryLock可轮询可中断可定时的锁

阅读更多

1、从JAVA5.0开始,提供了新的选择:ReentrantLock。

2、可定时和可轮询的锁获取模式由tryLock方法实现。

3、使用tryLock试图获得的锁如果不能同时获得,就回退,并重新尝试。休眠时间由一个特定组件管理。(下面的代码完成转帐)

public boolean transferMoney(Account fromAcct,AccounttoAcct,DollarAmonunt amount,long timeout,TimeUnit unit)

   throwsInsufficientFundsException,InterruptedException{

   longfixedDelay=getFixedDelayComponentNanos(timeout,unit);

   longrandMod=getRandomDelayModulusNanos(timeout,unit);

   longstopTime=System.nanoTime()+unit.toNanos(timeout);

 

   while (true){

      if (fromAcct.lock.tryLock()){

          try{

                 if(toAcct.lock.tryLock()){

                    try {

                           if (fromAcct.getBalance().compareTo(amount)<0)

                               thrownew  InsufficientFundsException();

                           else {

                                fromAcct.debit(amount);

                               toAcct.credit(amount);

                                returntrue;

                           }

                     }finally{toAcct.lock.unlock();}    

                }

          }finally{fromAcct.lock.unlock();}

      }

   }

   if(System.nanoTime()<stopTime) return false;

  NANOSECONDS.sleep(fixedDelay+rnd.nextLong()%randMod);
}

4、具有时间限制的活动,定时锁同样有用.超时后程序提前返回.

public boolean trySendOnSharedLine(String message,longtimeout,TimeUnit unit)

               throwsInterruptedException{

       longnanosToLock=unit.toNanos(timeout)-estimatedNanosToSend(message);

       if (!lock.tryLock(nanosToLock,NANOSECONDS)) return false;

       try{

             return sendOnSharedLine(message);

        }finally{lock.unlock();}

}

5、一个可中断的锁可以响应中断,能取消。

public boolean sendOnSharedLine(Stringmessage) 

      throws InterruptedException{

    lock.lockInterruptibly();

    try{

        return cancellableSendOnSharedLine(message);

    }finally{

        lock.unlock();

    }

}

private boolean cancellableSendOnSharedLine(String message)

    throwsInterruptedException{...}

}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics