Is java.lang.reflect.Method thread safe?

Is java.lang.reflect.Method thread java.lang.reflect.Method ?

The result of profiling my program showed that Class.getMethod() took a significant computational time when it was called many times, a little more than I expected. I can call this once and keep the resulting method somewhere easily accessible. But then several threads of web workers will use the stored Method object at the same time.

It is safe?

+6
java
source share
3 answers

The method is safe to use across multiple threads, provided that you do not change the state of the method after it is available to multiple threads. You can call setAccessible (true) and setAccessible (false) in two threads and the result will not be thread safe. However, this is not very useful.

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

+5
source share

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

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

+4
source share

The definition of the class will not change, therefore, if you do not load different classes in different streams (for example, from separate libraries), the Method object must be thread safe. (Of course, regardless of whether the method itself is called upon reflection to be thread safe, this is another question.)

0
source share

All Articles