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 whole team of agents - treating all new instances (of classes annotated with {@link AgentTeamScoped})
11   * as singletons for the purpose of construction of the team of agents.
12   * <p><p>
13   * Not all pogamut.base class is {@link AgentTeamScoped}.
14   * 
15   * @author Jimmy
16   */
17  public class AgentTeamScope implements IAgentScope {
18  	
19  	public static class SingletonProvider<T> implements Provider<T> {
20  		
21  		private Provider<T> creator;
22  		
23  		private T singleton = null;
24  		
25  		public SingletonProvider(Provider<T> creator) {
26  			this.creator = creator;
27  		}
28  
29  		@Override
30  		public T get() {
31  			if (singleton != null) {
32  				return singleton;
33  			}
34  			singleton = creator.get();
35  			return singleton;
36  		}
37  		
38  		public void clear() {
39  			singleton = null;
40  		}
41  		
42  	}
43  	
44  	@SuppressWarnings("unchecked")
45  	private Map<Key, Provider> providers = new HashMap<Key, Provider>(); 
46  
47  	@SuppressWarnings("unchecked")
48  	@Override
49  	public <T> Provider scope(Key<T> key, Provider<T> creator) {
50  		synchronized(providers) {
51  			Provider p = providers.get(key);
52  			if (p != null) { 
53  				return p;
54  			}
55  			SingletonProvider<T> provider = new SingletonProvider<T>(creator);
56  			providers.put(key, provider);
57  			return provider;
58  		}
59  	}
60  	
61  	@SuppressWarnings("unchecked")
62  	public void clearScope() {
63  		synchronized(providers) {
64  			for (Provider provider : providers.values()) {
65  				((SingletonProvider)provider).clear();
66  			}
67  		}
68  	}
69  
70  }