View Javadoc

1   package cz.cuni.amis.pogamut.base.utils.guice;
2   
3   import java.util.HashMap;
4   import java.util.Map;
5   
6   import com.google.inject.Key;
7   import com.google.inject.Provider;
8   
9   /**
10   * Scope used during the construction of the agent - treating all new instances (of classes annotated with {@link AgentScoped})
11   * as singletons.
12   * <p><p>
13   * After instantiation of the agent, Pogamut calls clearScope() to release all
14   * references to instantiated objects that allows to reuse the injector again
15   * to get another instance of the agent.
16   * <p><p>
17   * We need this, because we're usually have one connection object that must be injected
18   * into two different classes thus must be treated "as a singleton for one instantiation
19   * of the agent". (This is not the only example...)
20   * <p><p>
21   * Every pogamut.base class is {@link AgentScoped}.
22   * 
23   * @author Jimmy
24   *
25   */
26  public class AgentScope implements IAgentScope {
27  	
28  	public static class SingletonProvider<T> implements Provider<T> {
29  		
30  		private Provider<T> creator;
31  		
32  		private T singleton = null;
33  		
34  		public SingletonProvider(Provider<T> creator) {
35  			this.creator = creator;
36  		}
37  
38  		@Override
39  		public T get() {
40  			if (singleton != null) {
41  				return singleton;
42  			}
43  			singleton = creator.get();
44  			return singleton;
45  		}
46  		
47  		public void clear() {
48  			singleton = null;
49  		}
50  		
51  	}
52  	
53  	@SuppressWarnings("unchecked")
54  	private Map<Key, Provider> providers = new HashMap<Key, Provider>(); 
55  
56  	@SuppressWarnings("unchecked")
57  	@Override
58  	public <T> Provider scope(Key<T> key, Provider<T> creator) {
59  		synchronized(providers) {
60  			Provider p = providers.get(key);
61  			if (p != null) { 
62  				return p;
63  			}
64  			SingletonProvider<T> provider = new SingletonProvider<T>(creator);
65  			providers.put(key, provider);
66  			return provider;
67  		}
68  	}
69  	
70  	@SuppressWarnings("unchecked")
71  	public void clearScope() {
72  		synchronized(providers) {
73  			for (Provider provider : providers.values()) {
74  				((SingletonProvider)provider).clear();
75  			}
76  		}
77  	}
78  
79  }