java - Change final value compiled by JIT -


i noticed strange thing after changing final field via reflection, method returning field time giving old value. suppose might because of jit compiler.

here 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 = 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()); }  private static void removefinal(field field) throws nosuchfieldexception, illegalaccessexception {     field modifiersfield = field.class.getdeclaredfield("modifiers");     modifiersfield.setaccessible(true);     modifiersfield.setint(field, field.getmodifiers() & ~modifier.final); } } 

result is:

main@1be6f5c3 main@1be6f5c3 main@6b884d57 

i wondering, how can make getm() return updated value?

i wondering, how can make getm() return updated value?

with finals, can't. returning "old" value legitimate behavior, jls 17.5.3:

even then, there number of complications. if final field initialized constant expression (§15.28) in field declaration, changes final field may not observed, since uses of final field replaced @ compile time value of constant expression.

another problem specification allows aggressive optimization of final fields. within thread, permissible reorder reads of final field modifications of final field not take place in constructor.

see instructive example included in chapter.

attempts overcome provision have include messing optimizers down stack, , fragile @ best. if choosing modify fields, then, definition, fields should not final. if want performance reasons (do you, really?), jsr 292 provides mechanics "almost final" constructions.


Comments

Popular posts from this blog

c - How to retrieve a variable from the Apache configuration inside the module? -

c# - Constructor arguments cannot be passed for interface mocks -

python - malformed header from script index.py Bad header -