Question

The below text is from jls http://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html#jls-17.5.3

Even then, there are a number of complications. If a final field is initialized to a compile-time constant expression (§15.28) in the field declaration, changes to the final field may not be observed, since uses of that final field are replaced at compile time with the value of the constant expression.

Can anyone please give me better explanation for the above. I couldn't understand the statement "changes to the final field may not be observed". May with the help of example.

Was it helpful?

Solution

I couldn't understand the statement changes to the final field may not be observed

It tells that , if a final variable is declared as compile time constant then any change made in the final variable using reflection API further in program will not be visible to the program during execution.
For example consider the code given below:

import java.lang.reflect.*;
class ChangeFinal 
{
    private final int x = 20;//compile time constant
    public static void change(ChangeFinal cf)
    {
        try
        {
            Class clazz = ChangeFinal.class;
            Field field = clazz.getDeclaredField("x");
            field.setAccessible(true);
            field.set(cf , 190);//changed x to 190 for object cf
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
    }
    public static void main(String[] args) 
    {
        ChangeFinal cf = new ChangeFinal();
        System.out.println(cf.x);//prints 20
        change(cf);
        System.out.println(cf.x);//prints 20
    }
}

The Output of the above code is:

20
20

WHY?
The answer lies in the output provided by javap -c command for public static void main:

public static void main(java.lang.String[]);
  Code:
   0:   new     #3; //class ChangeFinal
   3:   dup
   4:   invokespecial   #11; //Method "<init>":()V
   7:   astore_1
   8:   getstatic       #12; //Field java/lang/System.out:Ljava/io/PrintStream;
   11:  aload_1
   12:  invokevirtual   #13; //Method java/lang/Object.getClass:()Ljava/lang/Cla
ss;
   15:  pop
   16:  bipush  20
   18:  invokevirtual   #14; //Method java/io/PrintStream.println:(I)V
   21:  aload_1
   22:  invokestatic    #15; //Method change:(LChangeFinal;)V
   25:  getstatic       #12; //Field java/lang/System.out:Ljava/io/PrintStream;
   28:  aload_1
   29:  invokevirtual   #13; //Method java/lang/Object.getClass:()Ljava/lang/Cla
ss;
   32:  pop
   33:  bipush  20
   35:  invokevirtual   #14; //Method java/io/PrintStream.println:(I)V
   38:  return

}

At line 16 (before changeFinal method is called)the value of cf.x is hardcoded to 20 . And at line 33 (after changeFinal method is called) the value of cf.x is again hardcoded to 20. Therefore , Although the change in the value of final variable x is done successfully by reflection API during execution, but because of x being a compile time constant it is showing its constant value 20.

OTHER TIPS

It means if in a class you have this:

public class Foo {
    public final boolean fooBoolean = true; // true is a constant expression
    public final int fooInt = 5; // 5 is a constant expression
}

At compile time any reference to Foo.fooBoolean may be replaced with true, and references to Foo.fooInt may be replaced by 5. If at runtime you later change either of those final fields via reflection, the code referencing it (as it was written) may never see it.

It is quite possible for a Java program to observe a final field having two different values at different times, even without reflection, without recompiling multiple versions of the class, and without anything along those lines. Consider the class below:

class X {
    static final int x = getX();
    
    static int getX() {
        System.out.println("X.x is now " + X.x);
        return 1;
    }
    
    public static void main(String[] args) {
        System.out.println("X.x is now " + X.x);
    }
}

Output:

X.x is now 0
X.x is now 1

This happens because some of the code (the first println) is executed before the field's value is assigned, so that code observes the field's default initial value of 0. The field has a default initial value before it is assigned, even though it is final, because it is not a constant field. The text you quoted from the JLS says this kind of thing cannot happen if the field is declared as a constant.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top