Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import org.openjdk.jmh.annotations.State;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.DependencyDescriptor;
import org.springframework.beans.factory.config.RuntimeBeanReference;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.RootBeanDefinition;
Expand Down Expand Up @@ -122,6 +123,35 @@ public Object singletLookupByTypeManyBeans(SingletonLookupState state) {
return state.beanFactory.getBean(B.class);
}

@State(Scope.Benchmark)
public static class PrimaryConflictState extends Shared {

@Param({"10", "1000"})
public int primaryBeans;

public DependencyDescriptor descriptor;

@Setup
public void setup() throws NoSuchFieldException {
this.beanFactory = new DefaultListableBeanFactory();
this.beanFactory.registerBeanDefinition("spouse", new RootBeanDefinition(TestBean.class));
// Primary singletons of an unrelated type, not instantiated yet
for (int i = 0; i < this.primaryBeans; i++) {
RootBeanDefinition rbd = new RootBeanDefinition(A.class);
rbd.setPrimary(true);
this.beanFactory.registerBeanDefinition("primary" + i, rbd);
}
this.beanFactory.freezeConfiguration();
this.descriptor = new DependencyDescriptor(TestBean.class.getDeclaredField("spouse"), true);
}
}

// Resolution by dependency name checks each primary bean for a conflict
@Benchmark
public Object resolveByNameWithPrimaryBeans(PrimaryConflictState state) {
return state.beanFactory.resolveDependency(state.descriptor, null);
}

static class A {
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
import java.util.concurrent.CompletionException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.function.Supplier;
Expand Down Expand Up @@ -192,6 +193,18 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
/** Cache of singleton-only bean names, keyed by dependency type. */
private final Map<Object, String[]> singletonBeanNamesByType = new ConcurrentReferenceHashMap<>(64);

/**
* Map of predicted types for primary singleton beans not instantiated yet, keyed by
* bean name, with {@code Void.class} for a primary bean whose type is not cached.
*/
private final Map<String, Class<?>> primaryPredictedTypes = new ConcurrentHashMap<>(16);

/**
* Incremented before cached predicted types of primary beans are discarded, so
* that a prediction computed concurrently is not cached afterwards.
*/
private final AtomicLong primaryPredictionGeneration = new AtomicLong();

/** List of bean definition names, in registration order. */
private volatile List<String> beanDefinitionNames = new ArrayList<>(256);

Expand Down Expand Up @@ -1455,6 +1468,16 @@ protected void checkForAliasCircle(String name, String alias) {
}
}

@Override
protected void afterSingletonCreation(String beanName) {
super.afterSingletonCreation(beanName);
// The predicted type of a primary bean may have changed during its creation
if (this.primaryBeanNamesWithType.containsKey(beanName)) {
this.primaryPredictionGeneration.incrementAndGet();
this.primaryPredictedTypes.remove(beanName);
}
}

@Override
protected void addSingleton(String beanName, Object singletonObject) {
super.addSingleton(beanName, singletonObject);
Expand Down Expand Up @@ -1532,6 +1555,8 @@ private void updateManualSingletonNames(Consumer<Set<String>> action, Predicate<
private void clearByTypeCache() {
this.allBeanNamesByType.clear();
this.singletonBeanNamesByType.clear();
this.primaryPredictionGeneration.incrementAndGet();
this.primaryPredictedTypes.clear();
}


Expand Down Expand Up @@ -2270,14 +2295,74 @@ private boolean hasPrimaryConflict(String beanName, Class<?> dependencyType) {
Class<?> candidateType = candidate.getValue();
if (!candidateName.equals(beanName) && (candidateType != Void.class ?
dependencyType.isAssignableFrom(candidateType) : // cached singleton class for primary bean
isTypeMatch(candidateName, dependencyType))) { // not instantiated yet or not a singleton
isPrimaryTypeMatch(candidateName, dependencyType))) { // not instantiated yet or not a singleton
return true;
}
}
return (getParentBeanFactory() instanceof DefaultListableBeanFactory parent &&
parent.hasPrimaryConflict(beanName, dependencyType));
}

/**
* Determine whether the given primary bean, which is not instantiated yet or not
* a singleton, matches the given dependency type.
* <p>Uses the predicted type of the bean if it may be cached (see
* {@link #getPrimaryPredictedType}), instead of {@link #isTypeMatch} which
* predicts the type again on every call.
*/
private boolean isPrimaryTypeMatch(String beanName, Class<?> dependencyType) {
Class<?> predictedType = getPrimaryPredictedType(beanName);
return (predictedType != null ? ClassUtils.isAssignable(dependencyType, predictedType) :
isTypeMatch(beanName, dependencyType));
}

/**
* Return the predicted type of the given primary bean, if it may be cached until
* the bean is instantiated (at which point its type is registered in
* {@link #primaryBeanNamesWithType}) or the by-type caches are cleared.
* <p>This is the case with a frozen configuration and no temporary class loader,
* for a singleton bean which is not a FactoryBean (whose object type may only
* become known later), has no singleton instance registered (to be matched
* instead), and is not currently in creation (where its predicted type may change,
* for example once its target type is resolved). Since such a change may outlast
* the creation, the predicted type is also discarded after each creation (see
* {@link #afterSingletonCreation}). Prototype and other scoped beans are excluded
* since their predicted type may change once an instance has been created.
* <p>For such a bean, matching a dependency type against the returned type is
* equivalent to {@link #isTypeMatch}.
* @param beanName the name of the primary bean
* @return the predicted type, or {@code null} if not cached
*/
private @Nullable Class<?> getPrimaryPredictedType(String beanName) {
long generation = this.primaryPredictionGeneration.get();
if (!isConfigurationFrozen() || getTempClassLoader() != null ||
containsSingleton(beanName) || isSingletonCurrentlyInCreation(beanName)) {
return null;
}
Class<?> predictedType = this.primaryPredictedTypes.get(beanName);
if (predictedType == null) {
try {
RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
if (mbd.isSingleton() && !isFactoryBean(beanName, mbd)) {
predictedType = predictBeanType(beanName, mbd, FactoryBean.class, Object.class);
}
}
catch (BeansException ex) {
// Not cached: let isTypeMatch handle it as usual
return null;
}
if (predictedType == null) {
predictedType = Void.class;
}
this.primaryPredictedTypes.put(beanName, predictedType);
if (this.primaryPredictionGeneration.get() != generation) {
// Overlapped a creation of the bean or a cache reset: may be stale afterwards
this.primaryPredictedTypes.remove(beanName, predictedType);
}
}
return (predictedType != Void.class ? predictedType : null);
}

/**
* Raise a NoSuchBeanDefinitionException or BeanNotOfRequiredTypeException
* for an unresolvable dependency.
Expand Down
Loading