Re: About "java.util.concurrent.Semaphore" design ...
Wesley Hall <noreply@example.com> wrote or quoted in
Message-ID: <45677b9b$0$8718$ed2619ec@ptn-nntp-reader02.plus.net>:
[snip]
The key part in the docs is this...
"When used in this way, the binary semaphore has the property (unlike
many Lock implementations), that the "lock" can be released by a thread
other than the owner (as semaphores have no notion of ownership)."
You are saying that you don't want this behaviour and so perhaps 'Locks'
are more appropriate than Semaphores. Under java.util.concurrent.locks
you will find classes that support locks that can maintain information
as to the owner thread. ...
It seems that the ownership of lock is not helpful to the
implementation of restricting the number of threads.
Let's consider the following case.
- Mother thread P.
- Her children thread C0, C1, C2. // MAX_AVAILABLE = 3
- Her children process resources simultaneously.
- She is informed of when all the children finish their tasks.
- Resource R0, R1, ... , Rn // ex: n > 100
The implementation of this case will be like:
<code_0>
//
// Mother thread P
//
ResourceSupplier rsup = ...;
void process() {
while (true) {
Resource R = rsup.offer();
if (R == null) break;
new Child_Thread( R ).start();
}
// All the resource are processed.
}
void anyResourceProcessed() {
rsup.processed();
}
//
// Child_Thread
//
class Child_Thread extends Thread {
....
public void run() {
// process R
anyResourceProcessed();
}
}
//
// ResourceSupplier
// (Exceptions were ignored for simplicity.)
//
class ResourceSupplier {
int count = 0;
int MAX_AVAILABLE = 3;
Queue<Resource> queue = ... // R0, R1, ... , Rn
synchronized Resource offer() {
if (count == MAX_AVAILABLE) {
wait();
}
Resource R = queue.offer();
if (R != null) {
count++;
return R;
}
// Code_Bock_A
while (count > 0) {
wait();
}
// All the resource are processed.
return null;
}
synchronized void processed() {
count--;
notify();
}
}
</code_0>
That is,
The ownership of lock has no correlation with the implementation
of restricting the number of threads. Any child thread can wake
"offer()" up. The semaphore concept is needed.
With the current "java.util.concurrent.Semaphore",
the implementation of the above case will be difficult
(Specially the implementation of "Code_Bock_A" and
debugging).