How does the JVM handle final variables differently under the hood?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
There is at least one section in the JVM specification about
final
's impact on the memory model, and it is quite important for multi-threaded code:final
fields of an object allow "safe publication":final
fields must be visible to all threads.final
reference are also guaranteed to be at least as up to date as when the constructor exits.final
and are either primitives or references to immutable objects) can be concurrently accessed without synchronization. It is also safe to read "effectively immutable" objects (ones whose fields aren't actuallyfinal
, but in practice never change) via afinal
reference.final
, then you must provide thread-safety by some other means.But note that the JVM does not enforce actual finality: You can re-assign values using reflection (which of course undermines the safe publication).