F
Frank Gerlach
There seem to be quite a number of not very clean and simple
implementations
of java Semaphores in the internet. The following example is extremely
simple (the Java 1.5 implementation is overfeatured IMHO) and correct:
/** Semaphore class for managing limited resources (such as database
* connections)
* Author: Frank Gerlach ([email protected])
* Copyright: None. Use in any way you want.
* located at: http://www.geocities.com/gerlachfrank/Semaphore.java
*/
public class Semaphore{
int count;
/** Create the semaphore
* @param initialcount number of resource items to manage
*/
public Semaphore(int initialcount){
count=initialcount;
}
/** Acquire one resource item
*/
public void P(){
synchronized(this){
if(count==0){
try{
wait();
}catch(InterruptedException ie){
//this should never happen
System.err.println("caught InterruptedException in
wait()");
}
}
count--;
}
}
/** Release one resource item, thereby waking up a sleeping thread
* if free resource count was zero.
*/
public void V(){
synchronized(this){
count++;
if(count==1)notify();
}
}
}
implementations
of java Semaphores in the internet. The following example is extremely
simple (the Java 1.5 implementation is overfeatured IMHO) and correct:
/** Semaphore class for managing limited resources (such as database
* connections)
* Author: Frank Gerlach ([email protected])
* Copyright: None. Use in any way you want.
* located at: http://www.geocities.com/gerlachfrank/Semaphore.java
*/
public class Semaphore{
int count;
/** Create the semaphore
* @param initialcount number of resource items to manage
*/
public Semaphore(int initialcount){
count=initialcount;
}
/** Acquire one resource item
*/
public void P(){
synchronized(this){
if(count==0){
try{
wait();
}catch(InterruptedException ie){
//this should never happen
System.err.println("caught InterruptedException in
wait()");
}
}
count--;
}
}
/** Release one resource item, thereby waking up a sleeping thread
* if free resource count was zero.
*/
public void V(){
synchronized(this){
count++;
if(count==1)notify();
}
}
}