开发者

Is java.lang.reflect.Method thread safe?

Is java.lang.reflect.Method thread safe?

Profiling result of my program showed that Class.getMethod() took considerable computing time when called many times, a little more than I expected. I can call this once and store the resulting method somewhere easily accessible. But then, multiple web worker threads will use the stored Method object concurrently.

Is thi开发者_StackOverflows safe?


The Method is safe to use accross multiple threads provided you don't change the Method's state after making it available to multiple threads.e.g. You can call setAccessible(true) and setAccessible(false) in two threads and the result would be not thread safe. However this has no really good use.

In short, Method.setAccessible() is not techincally thread safe, but you should be able to use it in a thread safe way.


Java classes are guaranteed to be defined only once per ClassLoader instance, so you can safely assume that the definition, including methods and their signatures will not change through time, so you can safely "cache" them for use by multiple threads.

However, keep in mind that classes with the same fully qualified name (package + class name) can be defined differently by separate ClassLoader instances.


The class definition isn't going to change, so unless you are loading different classes in different threads (from separate libraries, say), the Method object should be thread safe. (Of course, whether the method itself being called by reflection is thread-safe is a different question.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜