On Sun, Nov 24, 2013 at 1:24 PM, Cédric Beust ♔ <ced...@beust.com> wrote:

> I would be totally on board with constructor injection if finalguaranteed 
> structural immutability, but all it does is guarantee reference
> immutability (“this field is only assigned once”), ...
>
That's *not* all it does. Final fields provide additional safety guarantees
even in the presence of data races involving a reference to the containing
object: As long as that reference isn't leaked during construction, the
final fields *and everything reachable through them* are guaranteed to be
properly constructed. The same is not true for non-final fields.

So if an object has a field *map* that is assigned to a HashMap built
during construction, say, and you accidentally pass a reference to that
object, *obj**,* to another thread (after construction) via a data race (no
*happens-before* edge), then *obj.map* in the new thread is guaranteed to
see the properly constructed HashMap only if the *map* field is final.

It might seem like a marginal advantage, but for some folks this additional
guarantee tips the scales in favor of final.

But I think the other argument that Tim (other Tim!) advanced is more
important: In addition to providing those guarantees, final clearly
declares your intent.

--tim

-- 
You received this message because you are subscribed to the Google Groups 
"google-guice" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to google-guice+unsubscr...@googlegroups.com.
To post to this group, send email to google-guice@googlegroups.com.
Visit this group at http://groups.google.com/group/google-guice.
For more options, visit https://groups.google.com/groups/opt_out.

Reply via email to