Lew wrote:
tan wrote:
If the intention behind final declarations was just to ensure the
atomicity of the atomic operations, it could also have been done by
not giving access to the underlying fields to outside packages. Or, am
I missing something here?
You are.
The access to the "underlying fields" is already restricted, so if a
subclass were to access them it would be through superclass methods.
However, if those methods could be overridden, it would be possible to
do so in a non-thread-safe manner. No access to "underlying fields"
is needed for that. It would be possible to break the semantics of
the superclass, even for single-threaded use. There's no way the
writer(s) of AtomicInteger can prevent that save by preventing the
methods from being overridden.
The explanation seems unsatisfactory, because it applies to *any*
overridable method of *any* class.
public boolean equals(Object obj) { return true; }
... is an egregious violation of every principle we all hold dear,
yet Java does not prevent someone from writing the obscenity. So,
what makes AtomicInteger special?
accepts the consequences. AtomicInteger is not intended for such usage.