samedi 26 mars 2016

Will reflection keeps the semantics of volatile in java

For example, when I modified a volatile field in one thread, the JMM would guarantee that then the new value will be visible to the other thread.

My question is, is this still true when I use reflection to modify the field?

The following code is just an example to show how reflection works.

import java.lang.reflect.Field;

public class ReflectionDemo {
    private volatile boolean flag = false;

    /**
     * using reflection to modify a filed
     *
     * @param target target object
     * @param value  new value
     */
    public static void modify(ReflectionDemo target, boolean value) {
        try {
            Field field = ReflectionDemo.class.getDeclaredField("flag");
            field.setAccessible(true);
            field.setBoolean(target, value);
        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        ReflectionDemo demo = new ReflectionDemo();
        System.out.println(demo.flag);

        ReflectionDemo.modify(demo, true);
        System.out.println(demo.flag);
    }

}





Aucun commentaire:

Enregistrer un commentaire