View Javadoc

1   package org.sourceforge.jemm.client.id;
2   
3   import java.util.HashSet;
4   import java.util.Set;
5   
6   import org.sourceforge.jemm.client.shared.WeakSingletonFactory;
7   import org.sourceforge.jemm.types.ID;
8   
9   /**
10   * A Factory which creates a Flyweight of TrackedIDs such that
11   * two different ID objects, new ID(1) and new ID(1) will both
12   * map to the same TrackedID(1) object.
13   * 
14   * This is flyweight like pattern is used to allow reliable
15   * tracking of IDs on the client side such that when an ID
16   * is no longer being used the server can be told that this client
17   * is no longer holding a reference to an object with that ID or the
18   * ID itself for some purpose.
19   * 
20   * It is important that TrackedID's never get created any other way
21   * than via this Factory, and that normal ID instances do not get into
22   * the ShadowObject.
23   * 
24   * This class is thread safe.
25   * 
26   * @author Paul Keeble
27   *
28   */
29  public class TrackedIDFactoryImpl extends WeakSingletonFactory<ID, TrackedID> implements TrackedIDFactory {
30  	
31  	protected final Set<TrackedIDListener> listeners;
32  	
33  	/**
34  	 * Creates a new Factory with no ids mapped
35  	 */
36  	public TrackedIDFactoryImpl() {
37  		listeners = new HashSet<TrackedIDListener>();
38  	}
39  	
40  	@Override
41  	protected void notifyExpired(ID id) {
42  	    synchronized (listeners) {
43  	        for(TrackedIDListener l : listeners)
44  	            l.expired(id);
45          }
46  	}
47  	
48  	public void addListener(TrackedIDListener listener) {
49          synchronized (listeners) {
50              listeners.add(listener);
51          }
52  	}
53  	
54  	public synchronized void removeListener(TrackedIDListener listener) {
55          synchronized (listeners) {
56              listeners.remove(listener);
57          }
58  	}
59  
60  	@Override
61  	protected TrackedID createValue(ID id) {
62  		return new TrackedID(id);
63  	}
64  }