Should it be all fields, including super-fields, of a purposely immutable java class ‘final’ in order to be thread-safe or is it enough to have no modifier methods?
Suppose I have a POJO with non-final fields where all fields are type of some immutable class. This POJO has getters-setters, and a constructor which sets some initial value. If I extend this POJO with knocking out modifier methods, thus making it immutable, will extension class be thread-safe?
In order to use an effectively immutable object without
finalfields in a thread safe manner you need to use one of safe publication idioms when making the object available to other threads after initialization, otherwise these threads can see the object in partially initialized state (from Java Concurrency in Practice):Declaring fields of your immutable object as
finalreleases this restriction (i.e. it guarantees that if other threads see a reference to the object, they also see itsfinalfields in fully initialized state). However, in general case it doesn’t guarantee that other threads can see a reference to the object as soon as it was published, so you may still need to use safe publication to ensure it.Note that if your object implements an interface, you can use an approach used by
Collections.unmodifiableList(), etc: