OnJava8-Examples/lowlevel/AttemptLocking.java

61 lines
1.6 KiB
Java
Raw Normal View History

2016-12-07 10:34:41 -08:00
// lowlevel/AttemptLocking.java
2016-12-30 17:23:13 -08:00
// (c)2017 MindView LLC: see Copyright.txt
2015-11-15 15:51:35 -08:00
// We make no guarantees that this code is fit for any purpose.
2016-09-23 13:23:35 -06:00
// Visit http://OnJava8.com for more book information.
2015-06-15 17:47:35 -07:00
// Locks in the concurrent library allow you
2016-01-25 18:05:55 -08:00
// to give up on trying to acquire a lock
2015-06-15 17:47:35 -07:00
import java.util.concurrent.*;
import java.util.concurrent.locks.*;
2017-01-12 11:15:03 -08:00
import onjava.Nap;
2015-06-15 17:47:35 -07:00
public class AttemptLocking {
private ReentrantLock lock = new ReentrantLock();
public void untimed() {
boolean captured = lock.tryLock();
try {
System.out.println("tryLock(): " + captured);
} finally {
if(captured)
lock.unlock();
}
}
public void timed() {
boolean captured = false;
try {
captured = lock.tryLock(2, TimeUnit.SECONDS);
} catch(InterruptedException e) {
throw new RuntimeException(e);
}
try {
2016-01-25 18:05:55 -08:00
System.out.println(
"tryLock(2, TimeUnit.SECONDS): " + captured);
2015-06-15 17:47:35 -07:00
} finally {
if(captured)
lock.unlock();
}
}
public static void main(String[] args) {
final AttemptLocking al = new AttemptLocking();
al.untimed(); // True -- lock is available
al.timed(); // True -- lock is available
// Now create a separate task to grab the lock:
new Thread() {
{ setDaemon(true); }
@Override
public void run() {
al.lock.lock();
System.out.println("acquired");
}
}.start();
2017-01-12 11:15:03 -08:00
new Nap(10); // Give the 2nd task a chance
2015-06-15 17:47:35 -07:00
al.untimed(); // False -- lock grabbed by task
al.timed(); // False -- lock grabbed by task
}
2015-09-07 11:44:36 -06:00
}
/* Output:
2015-06-15 17:47:35 -07:00
tryLock(): true
tryLock(2, TimeUnit.SECONDS): true
tryLock(): true
tryLock(2, TimeUnit.SECONDS): true
2015-09-07 11:44:36 -06:00
*/