Could a final variable be reassigned in catch, even if assignment is last operation in try?

前端 未结 12 1163
粉色の甜心
粉色の甜心 2020-12-04 18:49

I am quite convinced that here

final int i;
try { i = calculateIndex(); }
catch (Exception e) { i = 1; }

i cannot possibly have

12条回答
  •  醉酒成梦
    2020-12-04 19:46

    I think there is one situation where this model act as life saver. Consider the code given below:

    final Integer i;
    try
    {
        i = new Integer(10);----->(1)
    }catch(Exception ex)
    {
        i = new Integer(20);
    }
    

    Now Consider the line (1). Most of the JIT compilers creates object in following sequence(psuedo code):

    mem = allocate();   //Allocate memory 
    ctorInteger(instance);//Invoke constructor for Singleton passing instance.
    i = mem;        //Make instance i non-null
    

    But, some JIT compilers does out of order writes. And above steps is reordered as follows:

    mem = allocate();   //Allocate memory 
    i = mem;        //Make instance i non-null
    ctorInteger(instance);  //Invoke constructor for Singleton passing instance.
    

    Now suppose, the JIT performs out of order writes while creating the object in line (1). And suppose an exception is thrown while executing the constructor. In that case, the catch block will have i which is not null . If JVM doesn't follow this modal then in this case final variable is allowed to be assigned twice!!!

提交回复
热议问题