LazyCubicleMonkey
LazyCubicleMonkey

Reputation: 1243

Unsafe Class-loading Issue?

Unsafe has a method to ensure that classes are initialized:

Unsafe.ensureClassInitialized(Class) line: not available [native method]

I suspect that this type of initialization doesn't lock on the class like regular java class-loading because I've occasionally bumped into some impossible situations. I can give more details later if needed, but does anyone know if class-loading using Unsafe has quirks like that?

Btw, here's a short stack trace of how that class gets loaded up:

Unsafe.ensureClassInitialized(Class) line: not available [native method]               
UnsafeFieldAccessorFactory.newFieldAccessor(Field, boolean) line: 25
ReflectionFactory.newFieldAccessor(Field, boolean) line: 122    
Field.acquireFieldAccessor(boolean) line: 918    
Field.getFieldAccessor(Object) line: 899               
Field.get(Object) line: 358          

Upvotes: 5

Views: 1367

Answers (2)

JodaStephen
JodaStephen

Reputation: 63375

For reference and web seaches, it turns out that you can force class initialization without using Unsafe:

Class.forName(cls.getName(), true, cls.getClassLoader());

Not pretty, but it works.

Upvotes: 3

DNA
DNA

Reputation: 42597

There's a similar issue here: https://issues.apache.org/bugzilla/show_bug.cgi?id=43867 (search for "Unsafe" to jump to the relevant section) which might be of assistance, though it's hard to tell without more context and code...

Tomcat, in the desire to clear out the static fields within a class by using reflection, has unwittingly caused the class init code to be rerun due to the way that reflection works. When it hits this code that tries to use the log factory, it doesn't know that it has already broken the logfactory by setting fields within the logfactory to null.

So clearing of fields by reflection (directly or by using Tomcat) could be an issue...

Upvotes: 0

Related Questions