Java Reference
In-Depth Information
«interface»
java.util.concurrent.locks.Lock
+
lock(): void
+
unlock(): void
+
newCondition(): Condition
Acquires the lock.
Releases the lock.
Returns a new
Condition
instance that is bound to this
Lock
instance.
java.util.concurrent.locks.ReentrantLock
+ReentrantLock()
+ReentrantLock(fair: boolean)
ReentrantLock(false)
Same as
.
Creates a lock with the given fairness policy. When the
fairness is true, the longest-waiting thread will get the
lock. Otherwise, there is no particular access order.
F
IGURE
30.13
The
ReentrantLock
class implements the
Lock
interface to represent a lock.
ReentrantLock
is a concrete implementation of
Lock
for creating mutually exclusive
locks. You can create a lock with the specified
fairness policy
. True fairness policies guar-
antee that the longest-waiting thread will obtain the lock first. False fairness policies grant a
lock to a waiting thread arbitrarily. Programs using fair locks accessed by many threads may
have poorer overall performance than those using the default setting, but they have smaller
variances in times to obtain locks and prevent starvation.
Listing 30.5 revises the program in Listing 30.7 to synchronize the account modification
using explicit locks.
fairness policy
L
ISTING
30.5
AccountWithSyncUsingLock.java
1
import
java.util.concurrent.*;
2
import
java.util.concurrent.locks.*;
3
4
public class
AccountWithSyncUsingLock {
5
package for locks
private static
Account account =
new
Account();
6
7
public static void
main(String[] args) {
8 ExecutorService executor = Executors.newCachedThreadPool();
9
10
// Create and launch 100 threads
11
for
(
int
i =
0
; i <
100
; i++) {
12 executor.execute(
new
AddAPennyTask());
13 }
14
15 executor.shutdown();
16
17
// Wait until all tasks are finished
18
while
(!executor.isTerminated()) {
19 }
20
21 System.out.println(
"What is balance? "
+ account.getBalance());
22 }
23
24
// A thread for adding a penny to the account
25
public static class
AddAPennyTask
implements
Runnable {
26
public void
run() {
27 account.deposit(
1
);
28 }
29 }
30
Search WWH ::
Custom Search