



Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
How to implement counting semaphores and mutex locks in java using the java built-in synchronization constructs. It covers the classes countingsemaphore and mutexlock, their methods p() and v(), and the use of java's wait and notify operations for mutual exclusion and thread synchronization.
Typology: Study notes
1 / 5
This page cannot be seen from the preview
Don't miss anything!




3.6 Semaphores and Locks in Java The Java language does not provide a semaphore construct, but Java’s built-in synchronizationconstructs can be used to simulate counting and binary semaphores.J2SE 5.0 (Java 2 Platform, Standard Edition 5.0) introduces package
java.util.concurrent
which contains a collection of synchronization classes, including classes
Semaphore
and
ReentrantLock
Below is an abstract class named
semaphore
public abstract class semaphore {
protected abstract void P();protected abstract void V();protected semaphore(int initialPermits) {permits = initialPermits;}protected int permits;
3.6.1 Class
countingSemaphore
The implementations of methods
() and
() in class
countingSemaphore
are based on
Implementation 2 in Listing 3.3, which is reproduced below:// Implementation 2 uses a queue of blocked threads. The value of
permits
may be // negative.
P(): permits = permits - 1;
if (permits < 0) wait on a queue of blocked threads V():
permits = permits + 1;if (permits <= 0)
notify one waiting thread;
To complete this implementation:^
provide mutual exclusion for accessing shared variable
permits