Skip to content

Commit

Permalink
No need to use locks for reflection stuff. Use single-racy reads inst…
Browse files Browse the repository at this point in the history
…ead.
  • Loading branch information
turbanoff committed Apr 20, 2022
1 parent 816f585 commit 014ad9d
Showing 1 changed file with 13 additions and 13 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -1029,13 +1029,16 @@ public void flushGeneratedClassesFor(String className) {
}
}

private Unsafe unsafe;
private static Unsafe unsafe;
private static Method defineClassMethod;

private Unsafe getUnsafe() throws NoSuchFieldException, IllegalAccessException {
private static Unsafe getUnsafe() throws NoSuchFieldException, IllegalAccessException {
Unsafe unsafe = ClassLoaderWeavingAdaptor.unsafe;
if (unsafe == null) {
Field theUnsafeField = Unsafe.class.getDeclaredField("theUnsafe");
theUnsafeField.setAccessible(true);
return (Unsafe) theUnsafeField.get(null);
ClassLoaderWeavingAdaptor.unsafe = unsafe = (Unsafe) theUnsafeField.get(null);
return unsafe;
}
return unsafe;
}
Expand Down Expand Up @@ -1105,15 +1108,14 @@ private void defineClass(ClassLoader loader, String name, byte[] bytes, Protecti
}
} else {
try {
if (defineClassMethod == null) {
synchronized (lock) {
getUnsafe();
defineClassMethod =
Unsafe.class.getDeclaredMethod("defineClass", String.class,byte[].class,Integer.TYPE,Integer.TYPE, ClassLoader.class,ProtectionDomain.class);
}
Unsafe unsafe = getUnsafe();
Method defineClass = defineClassMethod;
if (defineClass == null) {
defineClass = Unsafe.class.getDeclaredMethod("defineClass", String.class,byte[].class,Integer.TYPE,Integer.TYPE, ClassLoader.class,ProtectionDomain.class);
defineClass.setAccessible(true);
defineClassMethod = defineClass;
}
defineClassMethod.setAccessible(true);
clazz = defineClassMethod.invoke(getUnsafe(), name,bytes,0,bytes.length,loader,protectionDomain);
clazz = defineClassMethod.invoke(unsafe, name,bytes,0,bytes.length,loader,protectionDomain);
} catch (LinkageError le) {
le.printStackTrace();
// likely thrown due to defining something that already exists?
Expand All @@ -1130,8 +1132,6 @@ private void defineClass(ClassLoader loader, String name, byte[] bytes, Protecti
trace.exit("defineClass", clazz);
}
}
static Method defineClassMethod;
private static final Object lock = new Object();


// /*
Expand Down

0 comments on commit 014ad9d

Please sign in to comment.