2016-12-07 10:34:41 -08:00
|
|
|
// lowlevel/AttemptLocking.java
|
2021-01-31 15:42:31 -07:00
|
|
|
// (c)2021 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
|
2017-01-12 16:49:36 -08:00
|
|
|
// Now create a second task to grab the lock:
|
|
|
|
CompletableFuture.runAsync( () -> {
|
2015-06-15 17:47:35 -07:00
|
|
|
al.lock.lock();
|
|
|
|
System.out.println("acquired");
|
2017-01-12 16:49:36 -08:00
|
|
|
});
|
2017-01-22 16:48:11 -08:00
|
|
|
new Nap(0.1); // Give the second 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
|
2017-01-12 16:49:36 -08:00
|
|
|
acquired
|
|
|
|
tryLock(): false
|
|
|
|
tryLock(2, TimeUnit.SECONDS): false
|
2015-09-07 11:44:36 -06:00
|
|
|
*/
|