Reuse generated entity instantiators from ClassGeneratingEntityInstantiator instances.

We now reuse generated ObjectInstantiator classes instead of attempting to redefine classes with the same name. Redefinition leads to LinkageError and thus to the use of reflection-based instantiators and an increased allocation rate due to the failed attempt of class redeclaration.

Closes: #2446.
This commit is contained in:
Mark Paluch
2021-09-09 15:18:30 +02:00
parent 242a71ca56
commit f4805503c8
2 changed files with 46 additions and 3 deletions

View File

@@ -130,6 +130,13 @@ class ClassGeneratingEntityInstantiator implements EntityInstantiator {
try {
return doCreateEntityInstantiator(entity);
} catch (Throwable ex) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(
String.format("Cannot create entity instantiator for %s. Falling back to ReflectionEntityInstantiator.",
entity.getName()),
ex);
}
return ReflectionEntityInstantiator.INSTANCE;
}
}
@@ -376,12 +383,22 @@ class ClassGeneratingEntityInstantiator implements EntityInstantiator {
@Nullable PreferredConstructor<?, ?> constructor) {
String className = generateClassName(entity);
Class<?> type = entity.getType();
ClassLoader classLoader = type.getClassLoader();
if (ClassUtils.isPresent(className, classLoader)) {
try {
return ClassUtils.forName(className, classLoader);
} catch (Exception o_O) {
throw new IllegalStateException(o_O);
}
}
byte[] bytecode = generateBytecode(className, entity, constructor);
Class<?> type = entity.getType();
try {
return ReflectUtils.defineClass(className, bytecode, type.getClassLoader(), type.getProtectionDomain(), type);
return ReflectUtils.defineClass(className, bytecode, classLoader, type.getProtectionDomain(), type);
} catch (Exception e) {
throw new IllegalStateException(e);
}