J
Jeff
For a specific producer to distribute to several consumers , I have a simple
extension of HashSet of consumers. However, a problem sometimes occurs
while a consumer is removing himself from the HashSet.
The problem occurs when distribute() calls the .eventObserved() method of
the consumer that is trying to remove himself. The .eventObserved() method
never returns. I think that is because the consumer's thread is waiting in
ConsumerSet's remove(). The producing caller and consumer are always
different threads.
To solve the problem, I'm considering having remove() spawn a thread to do
the remove so that remove does not wait on synchronized. distribute() is
called A LOT, but remove() is called rarely.
Because I use ConsumerSet extensively, I'd like to get some wiser opinions.
Is there a better solution, or at least more Java-like?
public class ConsumerSet extends HashSet {
public void distribute(Object message) {
synchronized( this ) {
for (Iterator i = iterator(); i.hasNext()
((Consumer) i.next()).eventObserved(message);
}
}
public void add( Consumer consumer ) {
synchronized (this) {
super.add( consumer );
}
}
public void remove( Consumer consumer ) {
synchronized ( this ) {
super.remove( consumer );
}
}
} // ConsumerSet
// usually be an extension of Thread
public interface Consumer {
/**
* Invoked when an event is observed
*/
public void eventObserved( Object toProcess );
}
extension of HashSet of consumers. However, a problem sometimes occurs
while a consumer is removing himself from the HashSet.
The problem occurs when distribute() calls the .eventObserved() method of
the consumer that is trying to remove himself. The .eventObserved() method
never returns. I think that is because the consumer's thread is waiting in
ConsumerSet's remove(). The producing caller and consumer are always
different threads.
To solve the problem, I'm considering having remove() spawn a thread to do
the remove so that remove does not wait on synchronized. distribute() is
called A LOT, but remove() is called rarely.
Because I use ConsumerSet extensively, I'd like to get some wiser opinions.
Is there a better solution, or at least more Java-like?
public class ConsumerSet extends HashSet {
public void distribute(Object message) {
synchronized( this ) {
for (Iterator i = iterator(); i.hasNext()
((Consumer) i.next()).eventObserved(message);
}
}
public void add( Consumer consumer ) {
synchronized (this) {
super.add( consumer );
}
}
public void remove( Consumer consumer ) {
synchronized ( this ) {
super.remove( consumer );
}
}
} // ConsumerSet
// usually be an extension of Thread
public interface Consumer {
/**
* Invoked when an event is observed
*/
public void eventObserved( Object toProcess );
}