Re: final and constructor, a Java Wart
Mark Thornton wrote:
Arne Vajh??j wrote:
I have never liked the "final on everything possible" approach.
Code clutter in my opinion.
Accidentally assigning to something that should not be changed
is not a common problem.
Final also has implications for the memory model and potentially affects
the generated code (since JSR-133). If you want to construct an
immutable object which will be passed between threads, then you should
use final on all the fields. Java then guarantees that, on completion of
the constructor, all threads will see the same values for those fields.
Just to clear up something all of us, including me, are eliding, 'final' by
itself doesn't guarantee read-onliness nor thread safety in all cases.
Not thread safe:
public class Foo
{
private final List <Bar> bars = buildBars();
private List <Bar> buildBars()
{
List <Bar> ret = new ArrayList <Bar> ();
// add elements to ret
return ret;
}
...
}
Thread safe:
public class Foo
{
private final List <Bar> bars =
Collections.unmodifiableList( buildBars() );
...
}
This caveat I believe to have been understood in this discussion, but let's
make it explicit this once just to be sure. So now when we talk about 'final'
guaranteeing read-onliness and thread safety, we know that we mean we also
take care of deep immutability with it.
--
Lew