具有非最终成员且没有mutator方法的类的线程安全 [英] Thread safety for classes with non-final members with no mutator methods

查看:143
本文介绍了具有非最终成员且没有mutator方法的类的线程安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于以下课程,使mNumSides最终的含义是什么? 线程安全性"会受到影响吗?

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

推荐答案

绝对. final关键字保证所有线程始终都看到相同的mNumSides值.关于final及其对内存模型的影响的更多信息

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.

在不使用final的情况下,该对象可能会不一致地发布到其他线程,并且有可能(虽然非常低)线程可能将mNumSides的值视为0而不是传入的numSides构造函数. 将其设置为volatilestatic也可以.

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.

这篇关于具有非最终成员且没有mutator方法的类的线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆