Briging ReadyForJVMCI closer to master

This commit is contained in:
Jaroslav Tulach
2017-11-29 06:30:41 +01:00
22 changed files with 851 additions and 309 deletions

View File

@@ -1045,6 +1045,11 @@ public class MethodInvokerRewriter {
throw new IllegalStateException("Unable to find classId for " + slashedclassname
+ " referenced from invokedynamic in " + this.methodname + "()");
}
if(typeRegistry.getReloadableType(classId) == null) {
// can't rewrite non-reloading type
super.visitInvokeDynamicInsn(name, desc, bsm, bsmArgs);
return;
}
// Initially only rewriting use of INVOKEDYNAMIC to support Lambda execution
// TODO support the more general invokedynamic usage

View File

@@ -166,8 +166,9 @@ public class ReloadableType {
this.typeRegistry = typeRegistry;
this.dottedtypename = dottedtypename;
this.slashedtypename = dottedtypename.replace('.', '/');
this.typedescriptor = (typeDescriptor != null ? typeDescriptor : typeRegistry.getExtractor().extract(
initialBytes, true));
this.typedescriptor = (typeDescriptor != null ? typeDescriptor
: typeRegistry.getExtractor().extract(
initialBytes, true));
this.interfaceBytes = InterfaceExtractor.extract(initialBytes, typeRegistry, this.typedescriptor);
this.bytesInitial = initialBytes;
rewriteCallSitesAndDefine();
@@ -544,12 +545,17 @@ public class ReloadableType {
private void reloadProxiesIfNecessary(String versionsuffix) {
ReloadableType proxy = typeRegistry.cglibProxies.get(this.slashedtypename);
if (proxy != null) {
if (GlobalConfiguration.isRuntimeLogging && log.isLoggable(Level.INFO)) {
log.log(Level.INFO, "Attempting reload of cglib proxy for type " + this.slashedtypename);
}
Object[] strategyAndGeneratorPair = CglibPluginCapturing.clazzToGeneratorStrategyAndClassGeneratorMap.get(
getClazz());
if (strategyAndGeneratorPair == null) {
if (log.isLoggable(Level.SEVERE)) {
log.severe(
"Unable to find regeneration methods for cglib proxies - proxies will be out of date for this type");
"Unable to find regeneration methods for cglib proxies - proxies will be out of date for type: "
+ getClazz());
}
return;
}
@@ -567,6 +573,9 @@ public class ReloadableType {
}
found.setAccessible(true);
byte[] bs = (byte[]) found.invoke(a, b);
if (GlobalConfiguration.isRuntimeLogging && log.isLoggable(Level.INFO)) {
log.log(Level.INFO, "Proxy regenerate successful for " + this.slashedtypename);
}
proxy.loadNewVersion(versionsuffix, bs);
proxy.runStaticInitializer();
}
@@ -596,6 +605,9 @@ public class ReloadableType {
}
}
byte[] bs = (byte[]) found.invoke(a, b);
if (GlobalConfiguration.isRuntimeLogging && log.isLoggable(Level.INFO)) {
log.log(Level.INFO, "Proxy (fastclass) regenerate successful for " + this.slashedtypename);
}
proxy.loadNewVersion(versionsuffix, bs);
proxy.runStaticInitializer();
}
@@ -612,10 +624,8 @@ public class ReloadableType {
if (relevantProxies != null) {
for (ReloadableType relevantProxy : relevantProxies) {
Class<?>[] interfacesImplementedByProxy = relevantProxy.getClazz().getInterfaces();
// check slashedname correct
// @SuppressWarnings("restriction")
byte[] newProxyBytes = sun.misc.ProxyGenerator.generateProxyClass(
relevantProxy.getSlashedName(),
// TODO confirm slashedname correct
byte[] newProxyBytes = Utils.generateProxyClass(relevantProxy.getSlashedName(),
interfacesImplementedByProxy);
relevantProxy.loadNewVersion(versionsuffix, newProxyBytes, true);
}

View File

@@ -44,6 +44,7 @@ import org.objectweb.asm.tree.AnnotationNode;
import org.objectweb.asm.tree.FieldNode;
import org.springsource.loaded.Utils.ReturnType.Kind;
import sun.misc.ProxyGenerator;
// TODO debugging tests - how is the experience? rewriting of field accesses will really
// affect field navigation in the debugger
@@ -1935,4 +1936,38 @@ public class Utils implements Opcodes, Constants {
cr.accept(v, 0);
return v.classname;
}
private static boolean checkedForNewProxyGenerateMethod = false;
private static Method newProxyGenerateMethod;
public static byte[] generateProxyClass(String slashedName, Class<?>[] interfacesImplementedByProxy) {
if (!checkedForNewProxyGenerateMethod) {
checkedForNewProxyGenerateMethod = true;
try {
newProxyGenerateMethod = ProxyGenerator.class.getDeclaredMethod("generateProxyClass", String.class,
Class[].class, Integer.TYPE);
}
catch (NoSuchMethodException nsme) {
// That's fine, we are early Java8 or before
}
}
if (newProxyGenerateMethod != null) {
try {
newProxyGenerateMethod.setAccessible(true);
byte[] bytes = (byte[]) newProxyGenerateMethod.invoke(null, slashedName, interfacesImplementedByProxy,
(Opcodes.ACC_PUBLIC | Opcodes.ACC_FINAL));
return bytes;
}
catch (Exception e) {
// Unexpected
throw new RuntimeException("Unexpected exception calling proxy generator ", e);
}
}
else {
return sun.misc.ProxyGenerator.generateProxyClass(
slashedName,
interfacesImplementedByProxy);
}
}
}

View File

@@ -19,23 +19,28 @@ package org.springsource.loaded.agent;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.MethodVisitor;
import org.springsource.loaded.Constants;
import org.springsource.loaded.GlobalConfiguration;
/**
* This bytecode rewriter intercepts calls to generate made in the CGLIB framework and allows us to record what
* generator is called to create the proxy for some type. The same generator can then be driven again if the type is
* reloaded.
*
*
* @author Andy Clement
* @since 0.8.3
*/
public class CglibPluginCapturing extends ClassVisitor implements Constants {
private static Logger log = Logger.getLogger(CglibPluginCapturing.class.getName());
public static Map<Class<?>, Object[]> clazzToGeneratorStrategyAndClassGeneratorMap = new HashMap<Class<?>, Object[]>();
public static Map<Class<?>, Object[]> clazzToGeneratorStrategyAndFastClassGeneratorMap = new HashMap<Class<?>, Object[]>();
@@ -68,11 +73,22 @@ public class CglibPluginCapturing extends ClassVisitor implements Constants {
return ((ClassWriter) cv).toByteArray();
}
@Override
public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
if (name.equals("create")) {
if (GlobalConfiguration.isRuntimeLogging && log.isLoggable(Level.INFO)) {
log.info("intercepting create method");
}
MethodVisitor mv = super.visitMethod(access, name, desc, signature, exceptions);
return new CreateMethodInterceptor(mv);
}
else if (name.equals("generate")) {
if (GlobalConfiguration.isRuntimeLogging && log.isLoggable(Level.INFO)) {
log.info("intercepting generate method");
}
MethodVisitor mv = super.visitMethod(access, name, desc, signature, exceptions);
return new GenerateMethodInterceptor(mv);
}
else {
return super.visitMethod(access, name, desc, signature, exceptions);
}
@@ -98,6 +114,9 @@ public class CglibPluginCapturing extends ClassVisitor implements Constants {
final boolean itf) {
super.visitMethodInsn(opcode, owner, name, desc, itf);
if (name.equals("generate")) {
if (GlobalConfiguration.isRuntimeLogging && log.isLoggable(Level.INFO)) {
log.info("intercepting call to generate in create method");
}
// Code that calls generate:
// ALOAD 0
// GETFIELD net/sf/cglib/core/AbstractClassGenerator.strategy : Lnet/sf/cglib/core/GeneratorStrategy;
@@ -108,22 +127,46 @@ public class CglibPluginCapturing extends ClassVisitor implements Constants {
"L" + prefix + "/cglib/core/GeneratorStrategy;");
mv.visitVarInsn(ALOAD, 0); // AbstractClassGenerator instance
mv.visitMethodInsn(INVOKESTATIC, "org/springsource/loaded/agent/CglibPluginCapturing", "record",
"(Ljava/lang/Object;Ljava/lang/Object;)V", false);//Lnet/sf/cglib/core/GeneratorStrategy;Lnet/sf/cglib/core/AbstractClassGenerator);");
"(Ljava/lang/Object;Ljava/lang/Object;)V", false);//Lnet/sf/cglib/core/GeneratorStrategy;Lnet/sf/cglib/core/AbstractClassGenerator);");
}
}
}
class GenerateMethodInterceptor extends MethodVisitor implements Constants {
public GenerateMethodInterceptor(MethodVisitor mv) {
super(ASM5, mv);
}
@Override
public void visitCode() {
mv.visitVarInsn(ALOAD, 0); // AbstractClassGenerator instance
mv.visitFieldInsn(GETFIELD, prefix + "/cglib/core/AbstractClassGenerator", "strategy",
"L" + prefix + "/cglib/core/GeneratorStrategy;");
mv.visitVarInsn(ALOAD, 0); // AbstractClassGenerator instance
mv.visitMethodInsn(INVOKESTATIC, "org/springsource/loaded/agent/CglibPluginCapturing", "record",
"(Ljava/lang/Object;Ljava/lang/Object;)V", false);//Lnet/sf/cglib/core/GeneratorStrategy;Lnet/sf/cglib/core/AbstractClassGenerator);");
}
}
/**
* The classloader for class artifacts is used to load the generated classes for call sites. We need to rewrite
* these classes because they may be either calling something that disappears on a later reload (so need to fail
* appropriately) or calling something that isnt there on the first load - in this latter case they are changed to
* route the dynamic executor method.
*
*
* @param a the GeneratorStrategy being used
* @param b the AbstractClassGenerator
*/
public static void record(Object a, Object b) {
// if (GlobalConfiguration.isRuntimeLogging && log.isLoggable(Level.INFO)) {
// log.info("recording invocation of generate with " + (a == null ? "null" : a.getClass().getName()) + " b="
// + (b == null ? "null" : b.getClass().getName()));
// }
// a is a Lnet/sf/cglib/core/GeneratorStrategy;
// b is a Lnet/sf/cglib/core/AbstractClassGenerator (or specifically net/sf/cglib/reflect/FastClass$Generator)
// a is something like 'UndeclaredThrowableStrategy'
@@ -134,7 +177,9 @@ public class CglibPluginCapturing extends ClassVisitor implements Constants {
Field f = b.getClass().getDeclaredField("superclass");
f.setAccessible(true);
Class<?> clazz = (Class<?>) f.get(b);
// System.out.println("Recording pair " + clazz.getName() + " > " + b);
if (GlobalConfiguration.isRuntimeLogging && log.isLoggable(Level.INFO)) {
log.info("recording pair " + clazz.getName() + " > " + b);
}
clazzToGeneratorStrategyAndClassGeneratorMap.put(clazz, new Object[] { a, b });
}
catch (Throwable re) {
@@ -146,7 +191,9 @@ public class CglibPluginCapturing extends ClassVisitor implements Constants {
Field f = b.getClass().getDeclaredField("type");
f.setAccessible(true);
Class<?> clazz = (Class<?>) f.get(b);
// System.out.println("Recording pair (fastclass) " + clazz.getName() + " > " + b);
if (GlobalConfiguration.isRuntimeLogging && log.isLoggable(Level.INFO)) {
log.info("recording pair (fastclass) " + clazz.getName() + " > " + b);
}
clazzToGeneratorStrategyAndFastClassGeneratorMap.put(clazz, new Object[] { a, b });
}
catch (Throwable re) {

View File

@@ -110,8 +110,8 @@ public class SpringPlugin implements LoadtimeInstrumentationPlugin, ReloadEventP
public byte[] modify(String slashedClassName, ClassLoader classLoader, byte[] bytes) {
if (GlobalConfiguration.isRuntimeLogging && log.isLoggable(Level.INFO)) {
log.info("loadtime modifying " + slashedClassName);
if ((GlobalConfiguration.isRuntimeLogging && log.isLoggable(Level.INFO)) || debug) {
log.info("SPRING_PLUGIN: loadtime modifying " + slashedClassName);
}
if (slashedClassName.equals("org/springframework/web/servlet/mvc/annotation/AnnotationMethodHandlerAdapter")) {
return bytesWithInstanceCreationCaptured(bytes, THIS_CLASS,
@@ -140,6 +140,9 @@ public class SpringPlugin implements LoadtimeInstrumentationPlugin, ReloadEventP
}
public static void recordRequestMappingHandlerMappingInstance(Object obj) {
if (debug) {
System.out.println("SPRING_PLUGIN: Recording request mapping handler mapping instance..." + obj);
}
requestMappingHandlerMappingInstances.add(obj);
}
@@ -163,7 +166,7 @@ public class SpringPlugin implements LoadtimeInstrumentationPlugin, ReloadEventP
// called by the modified code
public static void recordDefaultAnnotationHandlerMappingInstance(Object obj) {
if (debug) {
System.out.println("Recording new instance of DefaultAnnotationHandlerMappingInstance");
System.out.println("SPRING_PLUGIN: Recording new instance of DefaultAnnotationHandlerMappingInstance");
}
defaultAnnotationHandlerMappingInstances.add(obj);
}
@@ -188,7 +191,7 @@ public class SpringPlugin implements LoadtimeInstrumentationPlugin, ReloadEventP
return;
}
if (debug) {
System.out.println("ParameterNamesCache: Clearing parameter name discoverer caches");
System.out.println("SPRING_PLUGIN: ParameterNamesCache: Clearing parameter name discoverer caches");
}
if (parameterNamesCacheField == null) {
try {
@@ -207,7 +210,8 @@ public class SpringPlugin implements LoadtimeInstrumentationPlugin, ReloadEventP
Object o = parameterNamesCache.remove(clazz);
if (debug) {
System.out.println(
"ParameterNamesCache: Removed " + clazz.getName() + " from cache?" + (o != null));
"SPRING_PLUGIN: ParameterNamesCache: Removed " + clazz.getName() + " from cache?"
+ (o != null));
}
}
catch (IllegalAccessException e) {
@@ -230,7 +234,7 @@ public class SpringPlugin implements LoadtimeInstrumentationPlugin, ReloadEventP
Method removeMethod = Map.class.getDeclaredMethod("remove", Object.class);
Object ret = removeMethod.invoke(map, clazz);
if (GlobalConfiguration.debugplugins) {
System.err.println("SpringPlugin: clearing methodResolverCache for " + clazz.getName());
System.err.println("SPRING_PLUGIN: clearing methodResolverCache for " + clazz.getName());
}
if (GlobalConfiguration.isRuntimeLogging && log.isLoggable(Level.INFO)) {
log.info("cleared a cache entry? " + (ret != null));
@@ -342,7 +346,8 @@ public class SpringPlugin implements LoadtimeInstrumentationPlugin, ReloadEventP
// protected void detectHandlers() throws BeansException { is defined on AbstractDetectingUrlHandlerMapping
for (Object o : defaultAnnotationHandlerMappingInstances) {
if (debug) {
System.out.println("Invoking detectHandlers on instance of DefaultAnnotationHandlerMappingInstance");
System.out.println(
"SPRING_PLUGIN: Invoking detectHandlers on instance of DefaultAnnotationHandlerMappingInstance");
}
try {
Class<?> clazz_AbstractDetectingUrlHandlerMapping = o.getClass().getSuperclass();
@@ -360,50 +365,140 @@ public class SpringPlugin implements LoadtimeInstrumentationPlugin, ReloadEventP
}
}
@SuppressWarnings("rawtypes")
private void reinvokeInitHandlerMethods() {
// org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping (super AbstractHandlerMethodMapping) - call protected void initHandlerMethods() on it.
for (Object o : requestMappingHandlerMappingInstances) {
if (debug) {
System.out.println("Invoking initHandlerMethods on instance of RequestMappingHandlerMapping");
System.out.println(
"SPRING_PLUGIN: Invoking initHandlerMethods on instance of RequestMappingHandlerMapping");
}
Class<?> clazz_AbstractHandlerMethodMapping = null;
try {
Class<?> clazz_AbstractHandlerMethodMapping = o.getClass().getSuperclass().getSuperclass();
// private final Map<T, HandlerMethod> handlerMethods = new LinkedHashMap<T, HandlerMethod>();
Field field_handlerMethods = clazz_AbstractHandlerMethodMapping.getDeclaredField("handlerMethods");
field_handlerMethods.setAccessible(true);
Map m = (Map) field_handlerMethods.get(o);
m.clear();
Field field_urlMap = clazz_AbstractHandlerMethodMapping.getDeclaredField("urlMap");
field_urlMap.setAccessible(true);
m = (Map) field_urlMap.get(o);
m.clear();
Method method_initHandlerMethods = clazz_AbstractHandlerMethodMapping.getDeclaredMethod(
"initHandlerMethods");
method_initHandlerMethods.setAccessible(true);
method_initHandlerMethods.invoke(o);
}
catch (NoSuchFieldException nsfe) {
if (debug) {
if (nsfe.getMessage().equals("handlerMethods")) {
System.out.println(
"problem resetting request mapping handlers - unable to find field 'handlerMethods' on type 'AbstractHandlerMethodMapping' - you probably are not on Spring 3.1");
}
else {
System.out.println("problem resetting request mapping handlers - NoSuchFieldException: "
+ nsfe.getMessage());
}
}
clazz_AbstractHandlerMethodMapping = o.getClass().getSuperclass().getSuperclass();
}
catch (Exception e) {
if (debug) {
System.out.println("SPRING_PLUGIN: Unable to get to AbstractHandlerMethodMapping from RMHM");
}
if (GlobalConfiguration.debugplugins) {
e.printStackTrace();
}
}
if (clazz_AbstractHandlerMethodMapping != null) {
try {
// private final Map<T, HandlerMethod> handlerMethods = new LinkedHashMap<T, HandlerMethod>();
Field field_handlerMethods = clazz_AbstractHandlerMethodMapping.getDeclaredField("handlerMethods");
field_handlerMethods.setAccessible(true);
Map m = (Map) field_handlerMethods.get(o);
m.clear();
}
catch (NoSuchFieldException e) {
if (debug) {
System.out.println("SPRING_PLUGIN: Unable to find handlerMethods field to clear");
}
}
catch (Exception e) {
if (GlobalConfiguration.debugplugins) {
e.printStackTrace();
}
}
try {
Field field_urlMap = clazz_AbstractHandlerMethodMapping.getDeclaredField("urlMap");
field_urlMap.setAccessible(true);
Map m = (Map) field_urlMap.get(o);
m.clear();
}
catch (NoSuchFieldException e) {
if (debug) {
System.out.println("SPRING_PLUGIN: Unable to find urlMap field to clear");
}
}
catch (Exception e) {
if (GlobalConfiguration.debugplugins) {
e.printStackTrace();
}
}
clearMappingRegistry(o, clazz_AbstractHandlerMethodMapping);
try {
Method method_initHandlerMethods = clazz_AbstractHandlerMethodMapping.getDeclaredMethod(
"initHandlerMethods");
method_initHandlerMethods.setAccessible(true);
method_initHandlerMethods.invoke(o);
}
catch (Exception e) {
if (GlobalConfiguration.debugplugins || debug) {
e.printStackTrace();
}
}
}
}
}
// More recent Springs use a MappingRegistry - clear it out if we can get at it, otherwise on re-driving
// the initHandlerMethods below we will get an error about already existing mappings
private void clearMappingRegistry(Object o, Class<?> clazz_AbstractHandlerMethodMapping) {
if (debug) {
System.out.println("SPRING_PLUGIN: clearing out mapping registry...");
}
Object mappingRegistryInstance = null;
try {
Field field_mappingRegistry = clazz_AbstractHandlerMethodMapping.getDeclaredField("mappingRegistry");
field_mappingRegistry.setAccessible(true);
mappingRegistryInstance = field_mappingRegistry.get(o);
}
catch (NoSuchFieldException e) {
if (debug) {
System.out.println(
"SPRING_PLUGIN: Unable to get mappingRegistry field on AbstractHandlerMethodMapping");
}
}
catch (IllegalAccessException e) {
if (GlobalConfiguration.debugplugins || debug) {
System.out.println(
"SPRING_PLUGIN: Problem accessing mappingRegistry field on AbstractHandlerMethodMapping: ");
e.printStackTrace(System.out);
}
}
if (mappingRegistryInstance == null) {
return;
}
Class mappingRegistryClass = mappingRegistryInstance.getClass();
clearMapField(mappingRegistryClass, mappingRegistryInstance, "registry");
clearMapField(mappingRegistryClass, mappingRegistryInstance, "mappingLookup");
clearMapField(mappingRegistryClass, mappingRegistryInstance, "urlLookup");
clearMapField(mappingRegistryClass, mappingRegistryInstance, "nameLookup");
clearMapField(mappingRegistryClass, mappingRegistryInstance, "corsLookup");
if (debug) {
System.out.println("SPRING_PLUGIN: ... cleared out the mapping registry contents");
}
}
private void clearMapField(Class clazz, Object instance, String name) {
try {
Field field = clazz.getDeclaredField(name);
field.setAccessible(true);
Map m = (Map) field.get(instance);
m.clear();
}
catch (NoSuchFieldException e) {
if (debug) {
System.out.println("SPRING_PLUGIN: Unable to find field '" + name + "' to clear");
}
}
catch (Exception e) {
if (GlobalConfiguration.debugplugins || debug) {
e.printStackTrace();
}
}
}

View File

@@ -53,7 +53,7 @@ import org.springsource.loaded.TypeRegistry;
import org.springsource.loaded.Utils;
import org.springsource.loaded.infra.UsedByGeneratedCode;
import org.springsource.loaded.jvm.JVM;
import org.springsource.loaded.support.ConcurrentWeakIdentityHashMap;
/**
* The reflective interceptor is called to rewrite any reflective calls that are found in the bytecode. Intercepting the
@@ -84,7 +84,8 @@ public class ReflectiveInterceptor {
classToRType = Collections.synchronizedMap(new WeakHashMap<Class<?>, WeakReference<ReloadableType>>());
}
else {
classToRType = new WeakHashMap<Class<?>, WeakReference<ReloadableType>>();
classToRType = new ConcurrentWeakIdentityHashMap<Class<?>, WeakReference<ReloadableType>>();
// classToRType = new WeakHashMap<Class<?>, WeakReference<ReloadableType>>();
}
}
@@ -650,7 +651,7 @@ public class ReflectiveInterceptor {
*/
private static Field asSetableField(Field field, Object target, Class<?> valueType, Object value,
boolean makeAccessibleCopy)
throws IllegalAccessException {
throws IllegalAccessException {
// Must do the checks exactly in the same order as JVM if we want identical error messages.
// JVM doesn't do this, since it cannot happen without reloading, we do it first of all.
@@ -1054,7 +1055,7 @@ public class ReflectiveInterceptor {
c = jlClassGetDeclaredConstructor(clazz);
}
catch (NoSuchMethodException e) {
e.printStackTrace();
// e.printStackTrace();
throw Exceptions.instantiation(clazz);
}
c = asAccessibleConstructor(c, true);

View File

@@ -0,0 +1,271 @@
/*
* Copyright 2016 zhanhb.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springsource.loaded.support;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.util.AbstractMap;
import java.util.AbstractSet;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.lang.NullPointerException;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
*
* @author zhanhb
* @param <K>
* @param <V>
*/
public class ConcurrentWeakIdentityHashMap<K, V> extends AbstractMap<K, V>
implements ConcurrentMap<K, V> {
private final ConcurrentMap<Key<K>, V> map;
private final ReferenceQueue<K> queue = new ReferenceQueue<K>();
private transient Set<Map.Entry<K, V>> es;
public ConcurrentWeakIdentityHashMap(int initialCapacity) {
this.map = new ConcurrentHashMap<Key<K>, V>(initialCapacity);
}
@SuppressWarnings("CollectionWithoutInitialCapacity")
public ConcurrentWeakIdentityHashMap() {
this.map = new ConcurrentHashMap<Key<K>, V>();
}
@Override
public V get(Object key) {
purgeKeys();
return map.get(new Key<Object>(key, null));
}
@Override
public V put(K key, V value) {
purgeKeys();
return map.put(new Key<K>(key, queue), value);
}
@Override
public int size() {
purgeKeys();
return map.size();
}
@SuppressWarnings({"NestedAssignment", "element-type-mismatch"})
private void purgeKeys() {
Reference<? extends K> reference;
while ((reference = queue.poll()) != null) {
map.remove(reference);
}
}
@Override
@SuppressWarnings("NestedAssignment")
public Set<Map.Entry<K, V>> entrySet() {
Set<Map.Entry<K, V>> entrySet;
return ((entrySet = this.es) == null) ? es = new EntrySet() : entrySet;
}
@Override
public V putIfAbsent(K key, V value) {
purgeKeys();
return map.putIfAbsent(new Key<K>(key, queue), value);
}
@Override
public V remove(Object key) {
return map.remove(new Key<Object>(key, null));
}
@Override
public boolean remove(Object key, Object value) {
purgeKeys();
return map.remove(new Key<Object>(key, null), value);
}
@Override
public boolean replace(K key, V oldValue, V newValue) {
purgeKeys();
return map.replace(new Key<K>(key, null), oldValue, newValue);
}
@Override
public V replace(K key, V value) {
purgeKeys();
return map.replace(new Key<K>(key, null), value);
}
@Override
public boolean containsKey(Object key) {
purgeKeys();
return map.containsKey(new Key<Object>(key, null));
}
@Override
@SuppressWarnings("empty-statement")
public void clear() {
while (queue.poll() != null);
map.clear();
}
@Override
public boolean containsValue(Object value) {
purgeKeys();
return map.containsValue(value);
}
private static class Key<T> extends WeakReference<T> {
private final int hash;
Key(T t, ReferenceQueue<T> queue) {
super(t, queue);
if(t == null) {
throw new NullPointerException();
} else {
hash = System.identityHashCode(t);
}
}
@Override
public boolean equals(Object obj) {
return this == obj || obj instanceof Key && ((Key<?>) obj).get() == get();
}
@Override
public int hashCode() {
return hash;
}
}
private class Iter implements Iterator<Map.Entry<K, V>> {
private final Iterator<Map.Entry<Key<K>, V>> it;
private Map.Entry<K, V> nextValue;
Iter(Iterator<Map.Entry<Key<K>, V>> it) {
this.it = it;
}
@Override
public boolean hasNext() {
if (nextValue != null) {
return true;
}
while (it.hasNext()) {
Map.Entry<Key<K>, V> entry = it.next();
K key = entry.getKey().get();
if (key != null) {
nextValue = new Entry(key, entry.getValue());
return true;
} else {
it.remove();
}
}
return false;
}
@Override
public Map.Entry<K, V> next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
Map.Entry<K, V> entry = nextValue;
nextValue = null;
return entry;
}
@Override
public void remove() {
it.remove();
nextValue = null;
}
}
private class EntrySet extends AbstractSet<Map.Entry<K, V>> {
@Override
public Iterator<Map.Entry<K, V>> iterator() {
return new Iter(map.entrySet().iterator());
}
@Override
public int size() {
return ConcurrentWeakIdentityHashMap.this.size();
}
@Override
public void clear() {
ConcurrentWeakIdentityHashMap.this.clear();
}
@Override
@SuppressWarnings("element-type-mismatch")
public boolean contains(Object o) {
if (!(o instanceof Map.Entry)) {
return false;
}
Map.Entry<?, ?> e = (Map.Entry<?, ?>) o;
return ConcurrentWeakIdentityHashMap.this.get(e.getKey()) == e.getValue();
}
@Override
public boolean remove(Object o) {
if (!(o instanceof Map.Entry)) {
return false;
}
Map.Entry<?, ?> e = (Map.Entry<?, ?>) o;
return ConcurrentWeakIdentityHashMap.this.remove(e.getKey(), e.getValue());
}
}
private class Entry extends AbstractMap.SimpleEntry<K, V> {
private static final long serialVersionUID = 1L;
Entry(K key, V value) {
super(key, value);
}
@Override
public V setValue(V value) {
ConcurrentWeakIdentityHashMap.this.put(getKey(), value);
return super.setValue(value);
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Map.Entry) {
Map.Entry<?, ?> e = (Map.Entry<?, ?>) obj;
return getKey() == e.getKey() && getValue() == e.getValue();
}
return false;
}
@Override
public int hashCode() {
return System.identityHashCode(getKey())
^ System.identityHashCode(getValue());
}
}
}

View File

@@ -150,8 +150,8 @@ public class Java8 {
if (null == ownerRType || !ownerRType.hasBeenReloaded()) {
// target containing the reference/lambdaMethod has not been reloaded, no need to get over
// complicated.
Class<?> ownerClazz = ownerRType.getClazz();
implMethod = caller.findVirtual(ownerClazz, name, implMethodType);
Class<?> clazz = callerLoader.loadClass(owner.replace("/", "."));
implMethod = caller.findVirtual(clazz, name, implMethodType);
}
else {
MethodMember targetReferenceMethodMember = ownerRType.getCurrentMethod(name, descriptor);