java反射 构造方法,构造器类在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);

}

and then create new instances of MyClass like

myClass.newInstance(new Object(), "Test");

Is the above call to newInstance() thread-safe, given that myClass is static?

解决方案

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".

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值