为什么Object成员变量在Java中不是最终的和易变的? [英] Why can an Object member variable not be both final and volatile in Java?

查看:233
本文介绍了为什么Object成员变量在Java中不是最终的和易变的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果在一个类中我有一个ConcurrentHashMap实例,它将被多个线程修改和读取,我可能会这样定义:

If in a class I have a ConcurrentHashMap instance that will be modified and read by multiple threads I might define like this:

public class My Class {

    private volatile ConcurrentHashMap<String,String> myMap = new ConcurrentHashMap<String,String>();
...
}

添加 final 到myMap字段会导致错误,说我只能使用final或volatile。为什么不能兼得?

adding final to the myMap field results in an error saying I can only use final or volatile. Why can it not be both?

推荐答案

volatile 只与变量本身的修改,而不是它所引用的对象。拥有 final volatile 字段是没有意义的,因为无法修改最终字段。只需声明字段 final ,它应该没问题。

volatile only has relevance to modifications of the variable itself, not the object it refers to. It makes no sense to have a final volatile field because final fields cannot be modified. Just declare the field final and it should be fine.

这篇关于为什么Object成员变量在Java中不是最终的和易变的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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