Re: final and constructor, a Java Wart
Arne Vajh??j wrote:
And I would also prefer some more explicit synchronization over
final to ensure thread safeness. It makes it a lot easier the day
something non final has to be added.
That's just not the point of final as it relates to synchronization. 'final'
doesn't replace synchronization, it obviates the need for it with respect to
the attribute so declared.
The question of synchronization has to be settled variable by variable, or
more correctly, instance by instance. If a class declares four attributes,
all 'final', then the instances to which those variables point are
thread-safe. If later modification adds a fifth, non-'final' attribute, then
that attribute will require explicit synchronization. This is true
regardless. If a class declares four non-'final' attributes, then adds a
fifth one also not 'final', then that fifth attribute will require explicit
synchronization. A implies B; not-A implies B; therefore B.
If one gets used to treating an entire object as immutable because all its
attributes are 'final', then adds a non-'final' attribute, they've got to be
responsible for all client code that used to depend on immutability. That's
the breaks.
Even though perhaps explicit synchronization from day one would make such a
refactoring easier, it remains true that use of 'final' to make an object
read-only, therefore thread safe, is easier than explicit synchronization.
You'd have the world go through more effort on immutable objects in order to
protect them against a rare, possible, erroneous refactoring effort in the future.
In the real world as it really is right now, where Java has the keyword
'final' with its associated semantics, one has the convenience of making all
an object's attributes read-only and thread-safe, with all the safety,
efficiency and convenience that guarantees, weighed against the need to be
responsible if refactoring the class to violate that promise. That's the
tradeoff now, in Java as it is.
I'll live with that.
--
Lew