Hello,
I can't seem to find anything equivalent to a Semaphore in the Blackberry Java Reference. What am I missing? java.util.concurrent isn't even there.
Thanks! Sean
Hello,
I can't seem to find anything equivalent to a Semaphore in the Blackberry Java Reference. What am I missing? java.util.concurrent isn't even there.
Thanks! Sean
From Using Threads in J2ME Applications by Eric Giguere :
The monitor maintains a queue of waiting threads, allowing only one thread at a time to enter the block.
Because every Java object can act as a monitor, the java.lang.Object class defines three methods that expose this basic functionality: wait(), notify(), and notifyAll(). Any thread can suspend itself by calling an object's wait() method:
...
Object obj = .... // some object to use as a lock
synchronized( obj ){
// here is where you'd check obj's state
try {
obj.wait();
}
catch( InterruptedException e ){
}
}
...
The thread must lock the object before invoking its wait() method. It must also catch the java.lang.InterruptedException and deal appropriately with thread interruptions. The thread implicitly releases its lock on the object after it suspends itself.
The wait() method is overloaded: The thread can specify an optional timeout in milliseconds if it doesn't want to wait indefinitely.
Once a thread suspends itself, another thread releases it by invoking the same object's notify() or notifyAll() method:
...
Object obj = .... // same object used as lock!
synchronized( obj ){
obj.notify(); // or notifyAll
}
...
Again, the second thread must lock the object before calling notify() or notifyAll(). These two methods behave the same except that one wakes one waiting thread while the other wakes all waiting threads. The order in which threads are woken is not specified. Each newly woken thread must re-obtain its lock on the object before it can actually proceed, because its lock on the object was implicitly released when it suspended itself.
So for anyone who comes across this, coldice' excellent answer lead me to this page, which explains how to implement various types of Semaphores using the wait/notify primitives available in J2ME http://tutorials.jenkov.com/java-concurrency/semaphores.html. Thanks!