(no commit message)
[utils] / support / cdi / src / main / java / org / wamblee / inject / InjectorCache.java
1 /*
2  * Copyright 2005-2010 the original author or authors.
3  * 
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  * 
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  * 
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package org.wamblee.inject;
17
18 import java.util.Map;
19 import java.util.concurrent.ConcurrentHashMap;
20
21 import org.wamblee.cdi.CdiInjector;
22
23 /**
24  * Cache of {@link CdiInjector}s for efficiency to avoid duplicate analysis of a
25  * given class.
26  * 
27  * @author Erik Brakkee
28  */
29 public class InjectorCache {
30
31     private Map<String, Injector> injectors;
32
33     private InjectorFactory injectorFactory;
34
35     /**
36      * Constructs an empty cache.
37      * 
38      * @param aMgr
39      *            Bean manager.
40      */
41     public InjectorCache(InjectorFactory aInjectorFactory) {
42         injectorFactory = aInjectorFactory;
43         injectors = new ConcurrentHashMap<String, Injector>();
44     }
45
46     /**
47      * Gets the injector for a given class. This returns a cached injector or
48      * creates a new injector and caches it.
49      * 
50      * @param aClass
51      *            Class to find injector for.
52      * @return Injector.
53      */
54     public Injector getInjector(Class aClass) {
55         Injector injector = injectors.get(aClass.getName());
56         if (injector == null) {
57             // create and add injector
58             // NOTE: in rare circumstances this will lead to parallel
59             // creation of
60             // an injector for the same class. However, only one of them
61             // will be the final one
62             // in the map. There are no side effects of this duplicate
63             // creation of injectors.
64             injector = injectorFactory.create(aClass);
65             injectors.put(aClass.getName(), injector);
66         }
67         return injector;
68     }
69 }