samedi 16 janvier 2016

Change final value compiled by JIT

I noticed a very strange thing that after changing final field via Reflection, method returning that field is all the time giving old value. I suppose this might be because of JIT compiler.

Here is sample program:

public class Main
{
private static final Main m = new Main();
public static Main getM()
{
    return m;
}

public static void main(String args[]) throws Exception
{
    Main m = getM();
    int x = 0;
    for(int i = 0;i<10000000;i++)
    {
        if(getM().equals(m))
            x ++;
    }
    Field f = Main.class.getDeclaredField("m");
    f.setAccessible(true);
    removeFinal(f);
    Main main1 = new Main();
    f.set(null, main1);
    Main main2 = (Main) f.get(null);
    Main main3 = getM();
    System.out.println(main1.toString());
    System.out.println(main2.toString());
    System.out.println(main3.toString());
}
}

Result is:

Main@1be6f5c3
Main@1be6f5c3
Main@6b884d57

I am wondering, how can i make getM() return updated value?





Aucun commentaire:

Enregistrer un commentaire