4 ms·
This article fails to mention the main benefit of final - it gives you much stricter guarantees for concurrency under the Java Memory Model. If you create an im
by lemming 17y ago
This article fails to mention the main benefit of final - it gives you much stricter guarantees for concurrency under the Java Memory Model. If you create an immutable object and the fields are final, you can immediately pass the object to another thread without synchronisation - this is not safe if the fields are not final but are otherwise immutable.
For this reason we enforce that all object member fields must be final if possible, but we don't enforce it for local variables or method parameters. There are benefits to be had by doing that as well but IMO the benefit outweighs the return (and our IDE, IntelliJ, warns us if we reuse a local variable or method parameter).