diff --git a/spring-beans/src/jmh/java/org/springframework/beans/factory/DefaultListableBeanFactoryBenchmark.java b/spring-beans/src/jmh/java/org/springframework/beans/factory/DefaultListableBeanFactoryBenchmark.java index b73059b6d7ac..1576b928e717 100644 --- a/spring-beans/src/jmh/java/org/springframework/beans/factory/DefaultListableBeanFactoryBenchmark.java +++ b/spring-beans/src/jmh/java/org/springframework/beans/factory/DefaultListableBeanFactoryBenchmark.java @@ -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; @@ -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 { } diff --git a/spring-beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java b/spring-beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java index 7cbfa7268008..79939a6b17ae 100644 --- a/spring-beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java +++ b/spring-beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java @@ -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; @@ -192,6 +193,18 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto /** Cache of singleton-only bean names, keyed by dependency type. */ private final Map 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> 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 beanDefinitionNames = new ArrayList<>(256); @@ -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); @@ -1532,6 +1555,8 @@ private void updateManualSingletonNames(Consumer> action, Predicate< private void clearByTypeCache() { this.allBeanNamesByType.clear(); this.singletonBeanNamesByType.clear(); + this.primaryPredictionGeneration.incrementAndGet(); + this.primaryPredictedTypes.clear(); } @@ -2270,7 +2295,7 @@ 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; } } @@ -2278,6 +2303,66 @@ private boolean hasPrimaryConflict(String beanName, Class dependencyType) { parent.hasPrimaryConflict(beanName, dependencyType)); } + /** + * Determine whether the given primary bean, which is not instantiated yet or not + * a singleton, matches the given dependency type. + *

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. + *

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. + *

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. diff --git a/spring-beans/src/test/java/org/springframework/beans/factory/support/PrimaryConflictResolutionTests.java b/spring-beans/src/test/java/org/springframework/beans/factory/support/PrimaryConflictResolutionTests.java new file mode 100644 index 000000000000..1cbf417f02db --- /dev/null +++ b/spring-beans/src/test/java/org/springframework/beans/factory/support/PrimaryConflictResolutionTests.java @@ -0,0 +1,411 @@ +/* + * Copyright and licensing information for this source code can be found in + * the NOTICE and LICENSE files distributed with this project. + */ + +package org.springframework.beans.factory.support; + +import java.lang.reflect.Field; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.FutureTask; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; + +import org.jspecify.annotations.Nullable; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import org.springframework.beans.factory.BeanCreationException; +import org.springframework.beans.factory.FactoryBean; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.config.BeanPostProcessor; +import org.springframework.beans.factory.config.DependencyDescriptor; +import org.springframework.beans.factory.config.SmartInstantiationAwareBeanPostProcessor; +import org.springframework.core.OverridingClassLoader; +import org.springframework.util.ReflectionUtils; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + +/** + * Tests for primary bean detection when a dependency is resolved by name in + * {@link DefaultListableBeanFactory}, with the predicted types of primary beans + * that are not instantiated yet cached for a frozen configuration. + * + *

Each test expects the same result as without caching. + * + * @author Eric Gross + */ +class PrimaryConflictResolutionTests { + + private static final long STEP_SECONDS = 20; + + + @Test + void primaryWinsOverNameMatch() { + DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); + registerAuditor(bf); + bf.registerBeanDefinition("primaryService", primary(new RootBeanDefinition(ServiceImpl.class))); + bf.freezeConfiguration(); + + assertThat(resolveAuditable(bf)).isEqualTo("serviceImpl"); + assertThat(resolveAuditable(bf)).isEqualTo("serviceImpl"); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void primaryTypePredictedOnceWithFrozenConfiguration(boolean freeze) { + DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); + AtomicInteger predictions = new AtomicInteger(); + bf.addBeanPostProcessor(new SmartInstantiationAwareBeanPostProcessor() { + @Override + public @Nullable Class predictBeanType(Class beanClass, String beanName) { + if (beanName.equals("primaryService")) { + predictions.incrementAndGet(); + } + return null; + } + }); + registerAuditor(bf); + bf.registerBeanDefinition("primaryService", servicePrimary(BeanDefinition.SCOPE_SINGLETON)); + if (freeze) { + bf.freezeConfiguration(); + } + + // Declared as Service: not a candidate for an Auditable before instantiation + assertThat(resolveAuditable(bf)).isEqualTo("auditor"); + int afterFirst = predictions.get(); + assertThat(afterFirst).isPositive(); + assertThat(resolveAuditable(bf)).isEqualTo("auditor"); + if (freeze) { + assertThat(predictions.get()).isEqualTo(afterFirst); + } + else { + assertThat(predictions.get()).isGreaterThan(afterFirst); + } + + bf.getBean("primaryService"); + assertThat(resolveAuditable(bf)).isEqualTo("serviceImpl"); + } + + @Test + void primaryTypeNotCachedWithTempClassLoader() { + DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); + registerAuditor(bf); + bf.registerBeanDefinition("primaryService", primary(new RootBeanDefinition(ServiceImpl.class.getName()))); + // Loads its own copies of ServiceImpl and its interfaces: not an Auditable here + bf.setTempClassLoader(new OverridingClassLoader(getClass().getClassLoader()) { + @Override + protected boolean isEligibleForOverriding(String className) { + return className.startsWith(PrimaryConflictResolutionTests.class.getName() + "$"); + } + }); + bf.freezeConfiguration(); + assertThat(resolveAuditable(bf)).isEqualTo("auditor"); + + bf.setTempClassLoader(null); + assertThat(resolveAuditable(bf)).isEqualTo("serviceImpl"); + } + + @Test + void primaryFactoryBeanWithObjectTypeKnownOnlyAfterInstantiation() { + DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); + registerAuditor(bf); + RootBeanDefinition rbd = primary(new RootBeanDefinition(LateTypedFactoryBean.class)); + rbd.getPropertyValues().add("ready", true); + bf.registerBeanDefinition("primaryFactory", rbd); + bf.freezeConfiguration(); + + assertThat(resolveAuditable(bf)).isEqualTo("serviceImpl"); + } + + @Test + void manualFactoryBeanSingletonForPrimaryDefinition() { + DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); + registerAuditor(bf); + bf.registerBeanDefinition("primaryFactory", primary(new RootBeanDefinition(Object.class))); + // Its object type is not known yet, so the primary bean type stays unresolved + LateTypedFactoryBean factory = new LateTypedFactoryBean(); + bf.registerSingleton("primaryFactory", factory); + bf.freezeConfiguration(); + assertThat(resolveAuditable(bf)).isEqualTo("auditor"); + + // Matched against the object type of the instance, not the bean definition + factory.setReady(true); + assertThat(resolveAuditable(bf)).isEqualTo("serviceImpl"); + } + + @Test + void primaryPrototypeWithBroaderDeclaredType() { + DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); + registerAuditor(bf); + bf.registerBeanDefinition("primaryService", servicePrimary(BeanDefinition.SCOPE_PROTOTYPE)); + bf.freezeConfiguration(); + + assertThat(resolveAuditable(bf)).isEqualTo("auditor"); + // Creating a prototype instance resolves the target type of the definition + assertThat(bf.getBean("primaryService")).isInstanceOf(ServiceImpl.class); + assertThat(resolveAuditable(bf)).isEqualTo("serviceImpl"); + } + + @Test + void primaryReplacedAfterResolution() { + DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); + registerAuditor(bf); + RootBeanDefinition unrelated = primary(new RootBeanDefinition(String.class, () -> "unrelated")); + bf.registerBeanDefinition("primaryService", unrelated); + bf.freezeConfiguration(); + assertThat(resolveAuditable(bf)).isEqualTo("auditor"); + + bf.removeBeanDefinition("primaryService"); + bf.registerBeanDefinition("primaryService", primary(new RootBeanDefinition(ServiceImpl.class))); + assertThat(resolveAuditable(bf)).isEqualTo("serviceImpl"); + } + + @Test + void primaryResolvedBetweenCreationAndRegistration() { + AtomicReference beforeRegistration = new AtomicReference<>(); + DefaultListableBeanFactory bf = new DefaultListableBeanFactory() { + @Override + protected void addSingleton(String beanName, Object singletonObject) { + if (beanName.equals("primaryService") && beforeRegistration.get() == null) { + beforeRegistration.set("pending"); + beforeRegistration.set(resolveAuditable(this)); + } + if (!containsSingleton(beanName)) { + super.addSingleton(beanName, singletonObject); + } + } + }; + registerAuditor(bf); + bf.registerBeanDefinition("primaryService", servicePrimary(BeanDefinition.SCOPE_SINGLETON)); + bf.freezeConfiguration(); + + // Predicted from the declared factory method return type before creation + assertThat(resolveAuditable(bf)).isEqualTo("auditor"); + bf.getBean("primaryService"); + // Predicted from the resolved target type after creation, before registration + assertThat(beforeRegistration.get()).isEqualTo("serviceImpl"); + assertThat(resolveAuditable(bf)).isEqualTo("serviceImpl"); + } + + @Test + @Timeout(60) + void primaryInCreationOnAnotherThread() throws Exception { + DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); + CountDownLatch instantiated = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + registerAuditor(bf); + bf.registerBeanDefinition("primaryService", servicePrimary(BeanDefinition.SCOPE_SINGLETON)); + bf.addBeanPostProcessor(new BeanPostProcessor() { + @Override + public Object postProcessBeforeInitialization(Object bean, String beanName) { + if (beanName.equals("primaryService")) { + instantiated.countDown(); + awaitQuietly(release); + } + return bean; + } + }); + bf.freezeConfiguration(); + assertThat(resolveAuditable(bf)).isEqualTo("auditor"); + + Thread creator = new Thread(() -> bf.getBean("primaryService"), "creator"); + FutureTask resolution = new FutureTask<>(() -> resolveAuditable(bf)); + Thread resolver = new Thread(resolution, "resolver"); + try { + creator.start(); + assertThat(instantiated.await(STEP_SECONDS, TimeUnit.SECONDS)).isTrue(); + + // The primary bean in creation on another thread has its target type resolved: + // it is a candidate, so it wins over the name match once created + resolver.start(); + awaitDoneOrWaiting(resolution, resolver); + release.countDown(); + assertThat(resolution.get(STEP_SECONDS, TimeUnit.SECONDS)).isEqualTo("serviceImpl"); + } + finally { + release.countDown(); + creator.join(TimeUnit.SECONDS.toMillis(STEP_SECONDS)); + } + assertThat(resolveAuditable(bf)).isEqualTo("serviceImpl"); + } + + + @Test + @Timeout(60) + void primaryPredictionOverlappingFailedCreationIsNotCached() throws Exception { + DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); + CountDownLatch predicted = new CountDownLatch(1); + CountDownLatch creationFailed = new CountDownLatch(1); + AtomicInteger initAttempts = new AtomicInteger(); + AtomicInteger resolverPredictions = new AtomicInteger(); + bf.addBeanPostProcessor(new SmartInstantiationAwareBeanPostProcessor() { + @Override + public @Nullable Class predictBeanType(Class beanClass, String beanName) { + // Pause the resolver in its second prediction (the first one is the FactoryBean + // check), once it has predicted the type to cache, before it caches it + if (beanName.equals("primaryService") && Thread.currentThread().getName().equals("resolver") && + resolverPredictions.incrementAndGet() == 2) { + predicted.countDown(); + awaitQuietly(creationFailed); + } + return null; + } + @Override + public Object postProcessBeforeInitialization(Object bean, String beanName) { + if (beanName.equals("primaryService") && initAttempts.getAndIncrement() == 0) { + throw new IllegalStateException("first creation fails"); + } + return bean; + } + }); + registerAuditor(bf); + bf.registerBeanDefinition("primaryService", servicePrimary(BeanDefinition.SCOPE_SINGLETON)); + bf.freezeConfiguration(); + + FutureTask resolution = new FutureTask<>(() -> resolveAuditable(bf)); + Thread resolver = new Thread(resolution, "resolver"); + try { + resolver.start(); + assertThat(predicted.await(STEP_SECONDS, TimeUnit.SECONDS)).isTrue(); + // Resolves the target type of the primary bean, then fails + assertThatExceptionOfType(BeanCreationException.class).isThrownBy(() -> bf.getBean("primaryService")); + } + finally { + creationFailed.countDown(); + } + // Predicted from the declared factory method return type before the creation + assertThat(resolution.get(STEP_SECONDS, TimeUnit.SECONDS)).isEqualTo("auditor"); + // Predicted again, from the resolved target type + assertThat(resolveAuditable(bf)).isEqualTo("serviceImpl"); + } + + private static RootBeanDefinition primary(RootBeanDefinition rbd) { + rbd.setPrimary(true); + return rbd; + } + + private static void registerAuditor(DefaultListableBeanFactory bf) { + bf.registerBeanDefinition("auditor", new RootBeanDefinition(AuditorImpl.class)); + } + + /** + * A primary bean declared as a {@link Service} through its factory method, + * creating a {@link ServiceImpl} which is also an {@link Auditable}. + */ + private static RootBeanDefinition servicePrimary(String scope) { + RootBeanDefinition rbd = primary(new RootBeanDefinition(Factories.class)); + rbd.setUniqueFactoryMethodName("createService"); + rbd.setScope(scope); + return rbd; + } + + /** + * Resolve an {@code Auditable} dependency named "auditor", returning the name of + * the injected bean, or the simple name of an exception thrown. + */ + private static String resolveAuditable(DefaultListableBeanFactory bf) { + Field field = ReflectionUtils.findField(AuditHolder.class, "auditor"); + DependencyDescriptor descriptor = new DependencyDescriptor(field, true); + try { + Object result = bf.resolveDependency(descriptor, "requestingBean"); + return (result instanceof Auditable auditable ? auditable.name() : result.getClass().getSimpleName()); + } + catch (RuntimeException ex) { + return ex.getClass().getSimpleName(); + } + } + + private static void awaitQuietly(CountDownLatch latch) { + try { + latch.await(STEP_SECONDS, TimeUnit.SECONDS); + } + catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + } + } + + /** + * Wait until the given task is done or its thread is waiting (for the bean in + * creation on another thread), so that it has made its resolution decision. + */ + private static void awaitDoneOrWaiting(FutureTask task, Thread thread) throws InterruptedException { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(STEP_SECONDS); + while (!task.isDone() && thread.getState() != Thread.State.WAITING && + thread.getState() != Thread.State.TIMED_WAITING && System.nanoTime() < deadline) { + Thread.sleep(10); + } + } + + + @SuppressWarnings("unused") + private static class AuditHolder { + + Auditable auditor; + } + + + interface Service { + } + + + interface Auditable { + + String name(); + } + + + static class ServiceImpl implements Service, Auditable { + + @Override + public String name() { + return "serviceImpl"; + } + } + + + static class AuditorImpl implements Auditable { + + @Override + public String name() { + return "auditor"; + } + } + + + static class Factories { + + static Service createService() { + return new ServiceImpl(); + } + } + + + /** + * Declares {@code FactoryBean}, so that its object type is only known + * once it has been instantiated and is "ready". + */ + static class LateTypedFactoryBean implements FactoryBean { + + private boolean ready; + + public void setReady(boolean ready) { + this.ready = ready; + } + + @Override + public Object getObject() { + return new ServiceImpl(); + } + + @Override + public @Nullable Class getObjectType() { + return (this.ready ? ServiceImpl.class : null); + } + } + +}