Buttercola: LinkedIn: Implement a Semaphore
LinkedIn: Implement a Semaphore
http://tutorials.jenkov.com/java-concurrency/semaphores.html
A Semaphore is a thread synchronization construct that can be used either to send signals between threads to avoid missed signals, or to guard a critical section like you would with a lock. Java 5 comes with semaphore implementations in the
Java 5 comes with a built-in
Using a semaphore like this you can avoid missed signals. You will call
The names
A Semaphore is a thread synchronization construct that can be used either to send signals between threads to avoid missed signals, or to guard a critical section like you would with a lock. Java 5 comes with semaphore implementations in the
java.util.concurrent
package so you don't have to implement your own semaphores. Still, it can be useful to know the theory behind their implementation and use. Java 5 comes with a built-in
Semaphore
so you don't have to implement your own. You can read more about it in the java.util.concurrent.Semaphore text, in my java.util.concurrent
tutorial.Semaphores
A Semaphore is a thread synchronization construct that can be used either to send signals between threads to avoid missed signals, or to guard a critical section like you would with a lock. Java 5 comes with semaphore implementations in the
java.util.concurrent
package so you don't have to implement your own semaphores. Still, it can be useful to know the theory behind their implementation and use.Java 5 comes with a built-in
Semaphore
so you don't have to implement your own. You can read more about it in the java.util.concurrent.Semaphore text, in my java.util.concurrent
tutorial.Simple Semaphore
Here is a simpleSemaphore
implementation:public class Semaphore { private boolean signal = false; public synchronized void take() { this.signal = true; this.notify(); } public synchronized void release() throws InterruptedException{ while(!this.signal) wait(); this.signal = false; } }The
take()
method sends a signal which is stored internally in the Semaphore
. The release()
method waits for a signal. When received the signal flag is cleared again, and the release()
method exited.Using a semaphore like this you can avoid missed signals. You will call
take()
instead of notify()
andrelease()
instead of wait()
. If the call to take()
happens before the call to release()
the thread callingrelease()
will still know that take()
was called, because the signal is stored internally in the signal
variable. This is not the case with wait()
and notify()
.The names
take()
and release()
may seem a bit odd when using a semaphore for signaling. The names origin from the use of semaphores as locks, as explained later in this text. In that case the names make more sense.Read full article from Buttercola: LinkedIn: Implement a Semaphore
No comments:
Post a Comment