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

会有一股神秘感。 提交于 2019-12-13 05:19:50

问题


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;
    }
}

回答1:


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.




回答2:


Num sides cannot be reassigned if it is declared as final. There'd be no risk of multiple threads reading different values due to it not being declared as volatile.

So, declaring the variable as final makes the class thread safe. As of now its not thread safe.

Declaring an object final keeps its reference from being reassigned, however if the object had internal data, that data could be reassigned which would not be thread-safe. This is an important point made by Colin on another answer.

In this case the data is a primitive, and so has no internal data. So here, declaring it final works fine.



来源:https://stackoverflow.com/questions/17623042/thread-safety-for-classes-with-non-final-members-with-no-mutator-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!