Search code examples
javathread-safetyimmutabilityfinal

Thread safety for classes with non-final members with no mutator methods


For the following class, what are the implications of making mNumSides final? Is "thread-safety" affected?

class Shape {
    private int mNumSides;

    public Shape(int numSides) {
        mNumSides = numSides;
    }

    public int getNumSides() {
        return mNumSides;
    }
}

Solution

  • Absolutely. final keyword guarantees that all the threads see the same value of mNumSides at all the times. More information on final and its impact on the Memory Model here.

    Without using final the object might be inconsistently published to other threads, and there is probability (extremely low though) that a thread might see the value of mNumSides as 0 rather than numSides as passed in constructor. Making it volatile or static will also work though.