Java – modify the final value compiled by JIT
•
Java
I noticed a very strange thing. After changing the last field through reflection, the method to return the field has always been the old value I think this may be because of the JIT compiler
The following is a 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()); } 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); } }
The result is:
Main@1be6f5c3 Main@1be6f5c3 Main@6b884d57
I want to know, how do I make getm () return an updated value?
Solution
In the final, you can't It is legal to return the "old" value, such as JLS 17.5 3:
Refer to the guidance examples included in this chapter
Attempts to overcome this requirement must involve mixing the optimizer with the stack and be the most vulnerable If you choose to modify fields, by definition, these fields should not be final If you want this performance reason (you, really?), Then, the mechanism provided by JSR 292 is built as "almost final"
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码