java-tryLock can be regularly polling the lock can be interrupted

2010-11-18  来源:本站原创  分类:Java  人气:109 

1, starting from the JAVA5.0 provides a new option: ReentrantLock.

2, timing and lock acquisition mode can be polled by the tryLock ways.

3, the use of the lock tryLock trying to get both if you can not get to back to back, and try again. Sleep time by a particular component management. (The following code to complete transfer)

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, time-bound activities, time locks are also useful. Timeouts early return after the procedure.

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, an interrupt can respond to interrupt the lock can be canceled.

public boolean sendOnSharedLine (Stringmessage)

throws InterruptedException {

lock.lockInterruptibly ();

try {

return cancellableSendOnSharedLine (message);

} Finally {

lock.unlock ();

}

}

private boolean cancellableSendOnSharedLine (String message)

throwsInterruptedException {...}

}

Turn http://deepfuture.javaeye.com/blog/599557

相关文章
  • java-tryLock can be regularly polling the lock can be interrupted 2010-11-18

    1, starting from the JAVA5.0 provides a new option: ReentrantLock. 2, timing and lock acquisition mode can be polled by the tryLock ways. 3, the use of the lock tryLock trying to get both if you can not get to back to back, and try again. Sleep time

  • Java multi-thread synchronization issues to explore (3. Lock came, we all get out of the [1. Understanding of re-entry lock]) 2009-11-26

    In the previous section, We have learned a Java multi-threaded programming keywords commonly used in synchronized, as well as the locking mechanism associated with the object. This section, let us get to know the new JDK 5 concurrency within the fram

  • Java multi-thread synchronization issues to explore (3. Lock came, we all get out of the [2. Fair or Unfair? It is a question ...]) 2009-11-18

    Let us continue in front of the ReentrantLock topic. First of all, ReentrantLock there is a Boolean parameter with a constructor, in the JDK official documents describe it like this: "Such a constructor accepts an optional fairness parameter. When se

  • Java blind spots: Double check the lock and the Singleton Pattern 2010-06-17

    Peter Haggar, Senior Software Engineer, IBM May 1, 2004 All programming languages have a number of common idioms. Understanding and using some idioms useful, programmers have to spend valuable time to create, learn and achieve these idioms. The probl

  • Java多线程(十)之ReentrantReadWriteLock深入分析 2013-08-30

    一.ReentrantReadWriteLock与ReentrantLock 说到ReentrantReadWriteLock,首先要做的是与ReentrantLock划清界限.它和后者都是单独的实现,彼此之间没有继承或实现的关系. ReentrantLock 实现了标准的互斥操作,也就是一次只能有一个线程持有锁,也即所谓独占锁的概念.前面的章节中一直在强调这个特点.显然这个特点在一定程度上面减低了吞吐量,实际上独占锁是一种保守的锁策略,在这种情况下任何"读/读","写/读&

  • java并发编程--AbstractQueuedSynchronizer加锁和解锁分析 2014-05-06

    在java.util.concurrent.locks包中有很多Lock的实现类,常用的有ReentrantLock.ReadWriteLock(实现类ReentrantReadWriteLock),其实现都依赖java.util.concurrent.AbstractQueuedSynchronizer类,实现思路都大同小异,因此我们以ReentrantLock作为讲解切入点. 1. ReentrantLock的调用过程 经过观察ReentrantLock把所有Lock接口的操作都委派到一个S

  • (Transfer) exploring ReentrantLock (re-entry lock) the topic of chapter leads 2010-09-02

    Keywords: thread carried over: http://www.crabone.com/index.php/2009/05/30/291.html Research has wanted to take the next ReentrantLock, her unique charm that I applied successfully, unfortunately it is not much online information can refer to, so he

  • Java并发编程--加锁机制初步,内置锁以及内置锁的重入 2012-10-30

    其实这一节要说的重点又是synchronized,因为和内置锁最相关的应该就是synchronized了.当然我们还是会从一些例子开始讲起.样例程序还是来自那本书: @NotThreadSafe public class UnsafeCachingFactorizer implements Servlet { private final AtomicReference<BigInteger> lastNumber = new AtomicReference<BigInteger>(

  • JAVA多线程-基础Synchronized 2012-11-07

    后篇: JAVA多线程-基础Lock Condition 并发集合 JAVA多线程-交互计算 Future Callable Promise 读懂代码,首先要懂得thread的几个状态,以及它们之间的转换. Java thread的状态有new, runnable, sleep, blocked,wait, interrupt, dead. t = new Thread() -> new t.start() -> runnable Synchronized(this) or lock.lock

  • 转:JVM中的另一种锁Lock的实现 2012-11-08

    前文(深入JVM锁机制-synchronized)分析了JVM中的synchronized实现,本文继续分析JVM中的另一种锁Lock的实现.与synchronized不同的是,Lock完全用Java写成,在java这个层面是无关JVM实现的. 在 java.util.concurrent.locks包中有很多Lock的实现类,常用的有ReentrantLock. ReadWriteLock(实现类ReentrantReadWriteLock),其实现都依赖 java.util.concurre

  • 转:java多线程小结,及解决应用挂死的问题 2013-08-08

    1.在Java程序中,JVM负责线程的调度.线程调度是指按照特定的机制为多个线程分配CPU的使用权. 调度的模式有两种:分时调度和抢占式调度.分时调度是所有线程轮流获得CPU使用权,并平均分配每个线程占用CPU的时间:抢占式调度是根据线程的优先级别来获取CPU的使用权.JVM的线程调度模式采用了抢占式模式. 2.Thread类实际上也是实现了Runnable接口的类. 在启动的多线程的时候,需要先通过Thread类的构造方法Thread(Runnable target) 构造出对象,然后调用Th

  • Beginners dwr push technology (to summarize) 2010-12-08

    Here is what I've seen in two small instances of online The first one: DWR2.0.x push technology to send a message to push for ChatRoom, stock information display scenes, better than now regularly polling the server side JS strategy, saving the server

  • Android 相关笔记 2013-03-25

    1.对文件进行读写枷锁,使用了nio技术 RandomAccessFile randomFile = null; byte[] buf = new byte[1024]; int count = 0; try { randomFile = new RandomAccessFile(new File(filePath), "rws"); FileChannel channel = randomFile.getChannel(); while ((count = is.read(buf))

  • 多线程:死锁 2014-07-08

    线程死锁DeadLock是一个令人头疼的问题,有时候很难重现.因为Java是单进程多线程语言,一旦死锁,有时候只能借助进程应用重启应用才能解决问题. 要达到死锁有四个条件: 1:互斥条件:一个资源每次只能被一个线程使用. 2:资源独占条件:一个线程因请求资源而阻塞时,对所持有的资源保持不放. 3:不剥削条件:线程已经获得的资源在未使用之前,不能被强行剥夺. 4:循环等待条件: 若干线程之间形成了一种头尾相接的循环等待资源关系. 要解决线程死锁就要从这四个条件入手.一般情况下可以: 1:避免或者减

  • 关于解除死锁的例子 2014-09-01

    下面例子用到 Java 并发工具java.util.concurrent.locks 包里的 Lock 接口和 ReentrantLock 类,ReentrantLock 类实现了Lock的接口.Lock 有一个很有用的方法 tryLock 尝试获取锁,如果可以获取到返回true,否则返回false. 具体过程还是看代码吧: package com.yao.thread; import java.util.concurrent.locks.Lock; import java.util.concu

  • 2000个软件开发领域的高频特殊词及精选例句(三) 2015-03-20

    superword是一个Java实现的英文单词分析软件,主要研究英语单词音近形似转化规律.前缀后缀规律.词之间的相似性规律等等. 551.单词 ibm 的匹配文本: The Basic Edition includes HDFS, Hbase, MapReduce, Hive, Mahout, Oozie, Pig, ZooKeeper, Hue, and several other open source tools, as well as a basic version of the IBM

  • Advanced Text Indexing with Lucene 2010-04-06

    Advanced Text Indexing with Lucene by Otis Gospodnetic 03/05/2003 Lucene Index Structure Lucene is a Free-text Indexing and-searching API written in Java. To appreciate Indexing techniques described later in this article, you need a Basic understandi

  • [Change] Multi-thread, have to say 2010-03-16

    Multi-threading thread: refers to the process of an implementation flow. The difference between threads and processes: each process requires the operating system to assign a separate memory address space, and the same process all the threads in the s

  • Talking about database transaction management 2010-09-07

    Overview <br /> Whether you use direct JDBC for database transaction handling, or use Spring-based EJB's declarative transaction or transaction management functionality, they are ultimately the underlying database using the transaction management ca

  • (转)Python线程指南 2012-02-21

    本文介绍了Python对于线程的支持,包括"学会"多线程编程需要掌握的基础以及Python两个线程标准库的完整介绍及使用示例. 注意:本文基于Python2.4完成,:如果看到不明白的词汇请记得百度谷歌或维基,whatever. 尊重作者的劳动,转载请注明作者及原文地址 >.< 1. 线程基础 1.1. 线程状态 线程有5种状态,状态转换的过程如下图所示: 1.2. 线程同步(锁) 多 线程的优势在于可以同时运行多个任务(至少感觉起来是这样).但是当线程需要共享数据时,可能