66import jakarta .enterprise .inject .spi .*;
77import jakarta .inject .Inject ;
88
9- import java .util .IdentityHashMap ;
109import java .util .Map ;
10+ import java .util .WeakHashMap ;
11+ import java .util .concurrent .locks .Lock ;
12+ import java .util .concurrent .locks .ReentrantLock ;
1113
1214/**
1315 * Allocator instance that ties into the CDI container.
1618 */
1719@ ApplicationScoped
1820public class CdiClassAllocator implements ClassAllocator {
19- private final Map <Class <?>, Bean <?>> classBeanMap = new IdentityHashMap <>();
21+ private final Map <Class <?>, Bean <?>> classBeanMap = new WeakHashMap <>();
22+ private final Lock lock = new ReentrantLock ();
2023 private final BeanManager beanManager ;
2124
2225 @ Inject
@@ -28,20 +31,25 @@ public CdiClassAllocator(@Nonnull BeanManager beanManager) {
2831 @ Override
2932 @ SuppressWarnings ("unchecked" )
3033 public <T > T instance (@ Nonnull Class <T > cls ) throws AllocationException {
34+ lock .lock ();
3135 try {
3236 // Create bean
3337 Bean <T > bean = (Bean <T >) classBeanMap .computeIfAbsent (cls , c -> {
34- AnnotatedType <T > annotatedClass = beanManager .createAnnotatedType (cls );
38+ // TODO bugged.
39+ // Equivalence check is based on the class name and does not include the loader.
40+ AnnotatedType <T > annotatedClass = beanManager .createAnnotatedType ((Class <T >) c );
3541 BeanAttributes <T > attributes = beanManager .createBeanAttributes (annotatedClass );
3642 InjectionTargetFactory <T > factory = beanManager .getInjectionTargetFactory (annotatedClass );
37- return beanManager .createBean (attributes , cls , factory );
43+ return beanManager .createBean (attributes , ( Class < T >) c , factory );
3844 });
3945 CreationalContext <T > creationalContext = beanManager .createCreationalContext (bean );
4046
4147 // Allocate instance of bean
4248 return bean .create (creationalContext );
4349 } catch (Throwable t ) {
4450 throw new AllocationException (cls , t );
51+ } finally {
52+ lock .unlock ();
4553 }
4654 }
4755}
0 commit comments