01: /*
02: * This software is OSI Certified Open Source Software.
03: * OSI Certified is a certification mark of the Open Source Initiative. The
04: * license (Mozilla version 1.0) can be read at the MMBase site. See
05: * http://www.MMBase.org/license
06: */
07: package org.mmbase.core.event;
08:
09: import java.util.*;
10:
11: import org.mmbase.util.logging.Logger;
12: import org.mmbase.util.logging.Logging;
13:
14: /**
15: * An EventBroker which administrates the listeners in a {@link java.util.WeakHashMap}. This means
16: * that such listeners can be garbage collected, even if they are still brokered.
17: *
18: * @author Michiel Meeuwissen
19: * @since MMBase-1.8.5
20: * @version $Id: WeakEventBroker.java,v 1.2 2007/07/26 14:08:53 michiel Exp $
21: */
22: public abstract class WeakEventBroker extends EventBroker {
23:
24: private static final Logger log = Logging
25: .getLoggerInstance(WeakEventBroker.class);
26:
27: private final Map<EventListener, Boolean> listeners = new WeakHashMap<EventListener, Boolean>();
28:
29: protected Collection<EventListener> backing() {
30: return listeners.keySet();
31: }
32:
33: public synchronized boolean addListener(EventListener listener) {
34: if (canBrokerForListener(listener)) {
35: if (listeners.containsKey(listener)) {
36: return false;
37: } else {
38: listeners.put(listener, null);
39: return true;
40: }
41: } else {
42: log.warn("Ignored listener for" + getClass()
43: + " because it cannot broker for that.");
44: }
45: return false;
46: }
47:
48: public synchronized void removeListener(EventListener listener) {
49: if (!listeners.remove(listener)) {
50: log.warn("Tried to remove " + listener + " from "
51: + getClass() + " but it was not found. Ignored.");
52: }
53:
54: }
55:
56: /**
57: * Only adds synchronization, because backing is not concurrency proof.
58: */
59: public synchronized void notifyForEvent(Event event) {
60: super .notifyForEvent(event);
61: }
62:
63: public String toString() {
64: return "Weak Event Broker";
65: }
66:
67: public static void main(String[] argv) {
68: Map<Object, Object> weakSet = new WeakHashMap<Object, Object>();
69: weakSet.put(new Object(), null);
70: System.out.println("set " + weakSet.keySet());
71: Runtime.getRuntime().gc();
72: System.out.println("set " + weakSet.keySet());
73: }
74:
75: }
|