构造器类在Java反射中的线程安全 [英] Constructor class thread safety in Java reflection
问题描述
使用 Java
反射,可以实例化类的对象,即使通过私有构造函数
Using Java
reflection, one can instantiate an object of a class, even via a private constructor, e.g. for
public class MyClass
{
private MyClass(Object p1, String p2)
{
// Constructor with no modifications to static code
}
}
one can do (in the same or any other class, exception handling omitted for simplification)
public static final Constructor myClass;
static
{
myClass = MyClass.class.getConstructor(Object.class, String.class);
myClass.setAccessible(true);
}
,然后创建 MyClass
like
and then create new instances of MyClass
like
myClass.newInstance(new Object(), "Test");
是上述调用 newInstance()
由于 myClass
是静态的
Is the above call to newInstance()
thread-safe, given that myClass
is static?
推荐答案
code> Constructor.newInstance()似乎不是严格的线程安全的;至少在我的openjdk-6实现中,我发现一个类 sun.reflect.NativeConstructorAccessorImpl
有一个字段定义为 private int numInvocations;
和稍后在这行代码: if(++ numInvocations> ReflectionFactory.inflationThreshold()){
- 这可能会如预期的行为。
同样,在 Constructor
类本身中,方法 acquireConstructorAccessor()
记录为这里没有同步。
Calling Constructor.newInstance()
does not seem to be strictly thread-safe; at least in my openjdk-6 implementation I find a class sun.reflect.NativeConstructorAccessorImpl
having a field defined as private int numInvocations;
and later on this line of code: if (++numInvocations > ReflectionFactory.inflationThreshold()) {
- which may certainly behave otherwise as expected.
Also, in the Constructor
class itself, the method acquireConstructorAccessor()
is documented with "NOTE that there is no synchronization used here".
但是,狡猾的行为似乎并没有导致一个完全意外的行为,只做重复/不必要的事情,因此调用 newInstance()
并行不会导致某些东西被破坏。
But the dodgy behaviour does not seem to result in an overall unexpected behavior, only doing things repeatedly/unnecessarily, thus calling newInstance()
in parallel would NOT result in something being screwed up.
显然,你仍然可以实例构造函数。
Obviously, you can still mess things up with what's done within the instance constructor.
这篇关于构造器类在Java反射中的线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!