Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ArC - cleanup and optimizations #11217

Merged
merged 1 commit into from
Aug 6, 2020
Merged
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 @@ -966,6 +966,13 @@ io.quarkus.arc.processor.ObserverRegistrar.RegistrationContext registerSynthetic
}

private void addSyntheticBean(BeanInfo bean) {
for (BeanInfo b : beans) {
mkouba marked this conversation as resolved.
Show resolved Hide resolved
if (b.getIdentifier().equals(bean.getIdentifier())) {
throw new IllegalStateException(
"A synthetic bean with identifier " + bean.getIdentifier() + " is already registered: "
+ b);
}
}
beans.add(bean);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,6 @@
import javax.enterprise.context.spi.Contextual;
import javax.enterprise.context.spi.CreationalContext;
import javax.enterprise.inject.IllegalProductException;
import javax.enterprise.inject.TransientReference;
import javax.enterprise.inject.literal.InjectLiteral;
import javax.enterprise.inject.spi.InterceptionType;
import javax.interceptor.InvocationContext;
Expand Down Expand Up @@ -245,6 +244,8 @@ Collection<Resource> generateSyntheticBean(BeanInfo bean) {
implementIsDefaultBean(bean, beanCreator);
}
implementGetKind(beanCreator, InjectableBean.Kind.SYNTHETIC);
implementEquals(bean, beanCreator);
implementHashCode(bean, beanCreator);

beanCreator.close();
return classOutput.getResources();
Expand Down Expand Up @@ -330,6 +331,9 @@ Collection<Resource> generateClassBean(BeanInfo bean, ClassInfo beanClass) {
implementIsDefaultBean(bean, beanCreator);
}

implementEquals(bean, beanCreator);
implementHashCode(bean, beanCreator);

beanCreator.close();
return classOutput.getResources();
}
Expand Down Expand Up @@ -428,6 +432,8 @@ Collection<Resource> generateProducerMethodBean(BeanInfo bean, MethodInfo produc
implementIsDefaultBean(bean, beanCreator);
}
implementGetKind(beanCreator, InjectableBean.Kind.PRODUCER_METHOD);
implementEquals(bean, beanCreator);
implementHashCode(bean, beanCreator);

beanCreator.close();
return classOutput.getResources();
Expand Down Expand Up @@ -512,6 +518,8 @@ Collection<Resource> generateProducerFieldBean(BeanInfo bean, FieldInfo producer
implementIsDefaultBean(bean, beanCreator);
}
implementGetKind(beanCreator, InjectableBean.Kind.PRODUCER_FIELD);
implementEquals(bean, beanCreator);
implementHashCode(bean, beanCreator);

beanCreator.close();
return classOutput.getResources();
Expand Down Expand Up @@ -1606,6 +1614,36 @@ protected void implementGetIdentifier(BeanInfo bean, ClassCreator beanCreator) {
getScope.returnValue(getScope.load(bean.getIdentifier()));
}

protected void implementEquals(BeanInfo bean, ClassCreator beanCreator) {
MethodCreator equals = beanCreator.getMethodCreator("equals", boolean.class, Object.class).setModifiers(ACC_PUBLIC);
// if (this == obj) {
// return true;
// }
equals.ifTrue(equals.invokeStaticMethod(MethodDescriptors.OBJECTS_REFERENCE_EQUALS, equals.getThis(),
equals.getMethodParam(0))).trueBranch().returnValue(equals.load(true));
// if (obj == null) {
// return false;
// }
equals.ifNull(equals.getMethodParam(0)).trueBranch().returnValue(equals.load(false));
// if (!(obj instanceof InjectableBean)) {
// return false;
// }
equals.ifFalse(equals.instanceOf(equals.getMethodParam(0), InjectableBean.class)).trueBranch()
.returnValue(equals.load(false));
// return identifier.equals(((InjectableBean) obj).getIdentifier());
ResultHandle injectableBean = equals.checkCast(equals.getMethodParam(0), InjectableBean.class);
ResultHandle otherIdentifier = equals.invokeInterfaceMethod(MethodDescriptors.GET_IDENTIFIER, injectableBean);
equals.returnValue(equals.invokeVirtualMethod(MethodDescriptors.OBJECT_EQUALS, equals.load(bean.getIdentifier()),
otherIdentifier));
}

protected void implementHashCode(BeanInfo bean, ClassCreator beanCreator) {
MethodCreator hashCode = beanCreator.getMethodCreator("hashCode", int.class).setModifiers(ACC_PUBLIC);
// return identifier.hashCode()
hashCode.returnValue(
hashCode.invokeVirtualMethod(MethodDescriptors.OBJECT_HASH_CODE, hashCode.load(bean.getIdentifier())));
}

/**
*
* @param bean
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -495,7 +495,7 @@ public String toString() {

@Override
public int hashCode() {
return Objects.hash(identifier);
return identifier.hashCode();
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,9 @@ Collection<Resource> generate(InterceptorInfo interceptor) {
implementIntercept(interceptorCreator, interceptor, providerTypeName, reflectionRegistration, isApplicationClass);
implementGetPriority(interceptorCreator, interceptor);

implementEquals(interceptor, interceptorCreator);
implementHashCode(interceptor, interceptorCreator);

interceptorCreator.close();
return classOutput.getResources();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import io.quarkus.arc.impl.InterceptorInvocation;
import io.quarkus.arc.impl.InvocationContexts;
import io.quarkus.arc.impl.MapValueSupplier;
import io.quarkus.arc.impl.Objects;
import io.quarkus.arc.impl.Reflections;
import io.quarkus.gizmo.MethodDescriptor;
import java.lang.reflect.Constructor;
Expand Down Expand Up @@ -75,10 +76,15 @@ public final class MethodDescriptors {
public static final MethodDescriptor OBJECT_EQUALS = MethodDescriptor.ofMethod(Object.class, "equals", boolean.class,
Object.class);

public static final MethodDescriptor OBJECT_HASH_CODE = MethodDescriptor.ofMethod(Object.class, "hashCode", int.class);

public static final MethodDescriptor OBJECT_TO_STRING = MethodDescriptor.ofMethod(Object.class, "toString", String.class);

public static final MethodDescriptor OBJECT_CONSTRUCTOR = MethodDescriptor.ofConstructor(Object.class);

public static final MethodDescriptor OBJECTS_REFERENCE_EQUALS = MethodDescriptor.ofMethod(Objects.class, "referenceEquals",
boolean.class, Object.class, Object.class);

public static final MethodDescriptor INTERCEPTOR_INVOCATION_POST_CONSTRUCT = MethodDescriptor.ofMethod(
InterceptorInvocation.class,
"postConstruct",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,30 +5,37 @@
import io.quarkus.arc.InjectableContext;
import java.util.Iterator;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import javax.enterprise.context.spi.Contextual;
import javax.enterprise.context.spi.CreationalContext;

abstract class AbstractSharedContext implements InjectableContext, InjectableContext.ContextState {

private final ComputingCache<Key<?>, ContextInstanceHandle<?>> instances;
private final ComputingCache<String, ContextInstanceHandle<?>> instances;

public AbstractSharedContext() {
this.instances = new ComputingCache<>(AbstractSharedContext::createInstanceHandle);
this.instances = new ComputingCache<>();
}

@SuppressWarnings("unchecked")
@Override
public <T> T get(Contextual<T> contextual, CreationalContext<T> creationalContext) {
return (T) instances.getValue(new Key<>(contextual, creationalContext)).get();
InjectableBean<T> bean = (InjectableBean<T>) contextual;
return (T) instances.computeIfAbsent(bean.getIdentifier(), new Supplier<ContextInstanceHandle<?>>() {
@Override
public ContextInstanceHandle<?> get() {
return createInstanceHandle(bean, creationalContext);
}
}).get();
}

@SuppressWarnings("unchecked")
@Override
public <T> T get(Contextual<T> contextual) {
ContextInstanceHandle<?> handle = instances.getValueIfPresent(new Key<>(contextual, null));
InjectableBean<T> bean = (InjectableBean<T>) contextual;
ContextInstanceHandle<?> handle = instances.getValueIfPresent(bean.getIdentifier());
return handle != null ? (T) handle.get() : null;
}

Expand All @@ -50,7 +57,8 @@ public boolean isActive() {

@Override
public void destroy(Contextual<?> contextual) {
ContextInstanceHandle<?> handle = instances.remove(new Key<>(contextual, null));
InjectableBean<?> bean = (InjectableBean<?>) contextual;
ContextInstanceHandle<?> handle = instances.remove(bean.getIdentifier());
if (handle != null) {
handle.destroy();
}
Expand Down Expand Up @@ -83,50 +91,9 @@ public void destroy(ContextState state) {
}

@SuppressWarnings({ "unchecked", "rawtypes" })
private static ContextInstanceHandle createInstanceHandle(Key key) {
InjectableBean<?> bean = (InjectableBean<?>) key.contextual;
return new ContextInstanceHandleImpl(bean, bean.create(key.creationalContext), key.creationalContext);
}

private static final class Key<T> {

private final Contextual<T> contextual;
private final CreationalContext<T> creationalContext;

Key(Contextual<T> contextual, CreationalContext<T> creationalContext) {
this.contextual = Objects.requireNonNull(contextual);
this.creationalContext = creationalContext;
}

@Override
public int hashCode() {
return contextual.hashCode();
}

@SuppressWarnings("rawtypes")
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof Key)) {
return false;
}
Key other = (Key) obj;
if (!contextual.equals(other.contextual)) {
return false;
}
return true;
}

@Override
public String toString() {
return "Key for " + contextual;
}

private static <T> ContextInstanceHandle createInstanceHandle(InjectableBean<T> bean,
CreationalContext<T> creationalContext) {
return new ContextInstanceHandleImpl(bean, bean.create(creationalContext), creationalContext);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;

/**
Expand All @@ -21,18 +22,45 @@
public class ComputingCache<K, V> {

private final ConcurrentMap<K, LazyValue<V>> map;
private final Function<K, V> computingFunction;

private final Function<K, LazyValue<V>> function;
/**
* Note that {@link #getValue(Object)} cannot be used if no default computing function is specified.
*/
public ComputingCache() {
this(null);
}

public ComputingCache(Function<K, V> computingFunction) {
this.map = new ConcurrentHashMap<>();
this.function = new CacheFunction(computingFunction);
this.computingFunction = computingFunction;
}

public V getValue(K key) {
return computeIfAbsent(key, computingFunction);
}

public V getValueIfPresent(K key) {
LazyValue<V> value = map.get(key);
return value != null ? value.getIfPresent() : null;
}

public V computeIfAbsent(K key, Function<? super K, ? extends V> computingFunction) {
return computeIfAbsent(key, new Supplier<V>() {
@Override
public V get() {
return computingFunction.apply(key);
}
});
}

public V computeIfAbsent(K key, Supplier<V> supplier) {
if (supplier == null) {
throw new IllegalStateException("Computing function not defined");
}
LazyValue<V> value = map.get(key);
if (value == null) {
value = function.apply(key);
value = new LazyValue<V>(supplier);
LazyValue<V> previous = map.putIfAbsent(key, value);
if (previous != null) {
value = previous;
Expand All @@ -41,11 +69,6 @@ public V getValue(K key) {
return value.get();
}

public V getValueIfPresent(K key) {
LazyValue<V> value = map.get(key);
return value != null ? value.getIfPresent() : null;
}

public V remove(K key) {
LazyValue<V> previous = map.remove(key);
return previous != null ? previous.get() : null;
Expand Down Expand Up @@ -86,19 +109,4 @@ public boolean isEmpty() {
return map.isEmpty();
}

class CacheFunction implements Function<K, LazyValue<V>> {

private final Function<K, V> computingFunction;

public CacheFunction(Function<K, V> computingFunction) {
this.computingFunction = computingFunction;
}

@Override
public LazyValue<V> apply(K key) {
return new LazyValue<V>(() -> computingFunction.apply(key));
}

}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package io.quarkus.arc.impl;

public final class Objects {

private Objects() {
}

// https://github.com/quarkusio/gizmo/issues/50
public static boolean referenceEquals(Object obj1, Object obj2) {
return obj1 == obj2;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package io.quarkus.arc.test.buildextension.beans;

import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;

import io.quarkus.arc.BeanCreator;
import io.quarkus.arc.processor.BeanRegistrar;
import io.quarkus.arc.test.ArcTestContainer;
import java.util.Map;
import javax.enterprise.context.spi.CreationalContext;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;

public class SyntheticBeanCollisionTest {

public static volatile boolean beanDestroyerInvoked = false;

@RegisterExtension
public ArcTestContainer container = ArcTestContainer.builder()
.beanRegistrars(new TestRegistrar()).shouldFail().build();

@Test
public void testFailure() {
assertNotNull(container.getFailure());
assertTrue(container.getFailure().getMessage().contains("A synthetic bean with identifier"),
container.getFailure().getMessage());
}

static class TestRegistrar implements BeanRegistrar {

@Override
public void register(RegistrationContext context) {
context.configure(String.class).unremovable().types(String.class).param("name", "Frantisek")
.creator(StringCreator.class).done();

context.configure(String.class).unremovable().types(String.class).param("name", "Martin")
.creator(StringCreator.class).done();
}

}

public static class StringCreator implements BeanCreator<String> {

@Override
public String create(CreationalContext<String> creationalContext, Map<String, Object> params) {
return "Hello " + params.get("name") + "!";
}

}

}