What does the JVM do with the final variable in the class?

How does the JVM handle final variables differently under the hood?

+4


source to share


1 answer


There is at least one section in the JVM specification on the impact final

on the memory model, and this is very important for multi-threaded code:

final

object fields allow "secure publication" :



  • When the constructor exits, all fields final

    should be visible to all threads.
  • The fields on any object that is accessed by reference final

    are also guaranteed to be at least as relevant as when the constructor exits.
  • Taken together, this means that immutable objects (those where all fields final

    are either primitives or references to immutable objects) can be simultaneously accessed without synchronization. It is also safe to read "effectively immutable" objects (those whose fields don't actually final

    change, but in practice never change) by reference final

    .
  • Conversely, if your object is accessed by multiple threads, and you do not declare its fields final

    , then you must provide thread protection in other ways.

But note that the JVM does not provide actual completeness: you can reassign values โ€‹โ€‹using reflection (which, of course, undermines safe publishing).

+6


source







All Articles