/* * Copyright 2005-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wamblee.inject; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * Cache of {@link CdiInjector}s for efficiency to avoid duplicate analysis of a * given class. * * @author Erik Brakkee */ public class InjectorCache { private Map injectors; private InjectorFactory injectorFactory; /** * Constructs an empty cache. * * @param aInjectorFactory Injector factory to create Injectors. */ public InjectorCache(InjectorFactory aInjectorFactory) { injectorFactory = aInjectorFactory; injectors = new ConcurrentHashMap(); } /** * Gets the injector for a given class. This returns a cached injector or * creates a new injector and caches it. * * @param aClass * Class to find injector for. * @return Injector. */ public Injector getInjector(Class aClass) { Injector injector = injectors.get(aClass.getName()); if (injector == null) { // create and add injector // NOTE: in rare circumstances this will lead to parallel // creation of // an injector for the same class. However, only one of them // will be the final one // in the map. There are no side effects of this duplicate // creation of injectors. injector = injectorFactory.create(aClass); injectors.put(aClass.getName(), injector); } return injector; } }