Java Reference
In-Depth Information
To create a semaphore, you have to specify the number of permits with an optional fair-
ness policy, as shown in FigureĀ 30.23. A task acquires a permit by invoking the semaphore's
acquire() method and releases the permit by invoking the semaphore's release()
method. Once a permit is acquired, the total number of available permits in a semaphore is
reduced by 1 . Once a permit is released, the total number of available permits in a semaphore
is increased by 1 .
java.util.concurrent.Semaphore
+Semaphore(numberOfPermits: int)
Creates a semaphore with the specified number of permits. The
fairness policy is false.
Creates a semaphore with the specified number of permits and
the fairness policy.
Acquires a permit from this semaphore. If no permit is
available, the thread is blocked until one is available.
Releases a permit back to the semaphore.
+Semaphore(numberOfPermits: int, fair:
boolean)
+acquire(): void
+release(): void
F IGURE 30.23
The Semaphore class contains the methods for accessing a semaphore.
A semaphore with just one permit can be used to simulate a mutually exclusive lock.
Listing 30.9 revises the Account inner class in Listing 30.9 using a semaphore to ensure that
only one thread at a time can access the deposit method.
L ISTING 30.9
New Account Inner Class
1 // An inner class for Account
2 private static class Account {
3
// Create a semaphore
4
private static Semaphore semaphore = new Semaphore( 1 );
create a semaphore
5
private int balance = 0 ;
6
7
public int getBalance() {
8
return balance;
9 }
10
11
public void deposit( int amount) {
12
try {
13
semaphore.acquire(); // Acquire a permit
acquire a permit
14
int newBalance = balance + amount;
15
16 // This delay is deliberately added to magnify the
17 // data-corruption problem and make it easy to see
18 Thread.sleep( 5 );
19
20 balance = newBalance;
21 }
22 catch (InterruptedException ex) {
23 }
24
finally {
25
semaphore.release(); // Release a permit
release a permit
26 }
27 }
28 }
A semaphore with one permit is created in line 4. A thread first acquires a permit when execut-
ing the deposit method in line 13. After the balance is updated, the thread releases the permit
in line 25. It is a good practice to always place the release() method in the finally clause
to ensure that the permit is finally released even in the case of exceptions.
 
 
Search WWH ::




Custom Search