Search code examples
javavariablesfinalsynchronized

Final variable and synchronized block in java


What is a final variable in Java? For example: if I write final int temp; in function what is the meaning of the final keyword?
Also, when would I want to use final variable (both as a class variable and as a function variable)?
Why must variables in a synchronized block be declared final?


Solution

  • Basically it just means you can't change the value. For instance variables, you have to assign any final variables once (and only once) in the constructor (or with a variable initializer). Synchronization is a pretty orthogonal concept.

    The primary reason for making a local variable final is so you can use it in an anonymous inner class... this has nothing to do with being in a synchronized block.

    Final variables are useful for immutable classes, admittedly - and immutability makes life easier in a multi-threaded environment - but that's the only relationship between the two that I can think of...

    EDIT: Wildwezyr's comment makes sense in terms of not changing the variable on which you are synchronizing. That would be dangerous, for the reasons he's given. Is that what you meant by "variable in synchronized block"?