How to ensure thread safety for Java reflection's set operation?

55 Views Asked by At

Is Field public void set(Object obj, Object value) thread-safe when using Java reflection? If it's not thread-safe, how can the atomicity of set be ensured?

Write rarely and read frequently, reads and writes are not in the same place, so it's not convenient to use synchronized access.

1

There are 1 best solutions below

0
Kayaman On

You can use VarHandle to perform finer-grained access to a variable than with default reflection.

Access to such variables is supported under various access modes, including plain read/write access, volatile read/write access, and compare-and-set.

You can also manually create load/store/full fences. Prerequisites are: understanding the Java Memory Model and concurrency in general.