java final 线程安全,Java并发:是final字段(在构造函数中初始化)线程安全?

Can anyone tell me whether this class is threadsafe or not ?

class Foo {

private final Map aMap;

public Foo() {

aMap = new HashMap();

aMap.put("1", "a");

aMap.put("2", "b");

aMap.put("3", "c");

}

public String get(String key) {

return aMap.get(key);

}

}

Edit: It my fault to not clarify the question. According to JMM FAQ :

A new guarantee of initialization safety should be provided. If an object is properly constructed (which means that references to it do not escape during construction), then all threads which see a reference to that object will also see the values for its final fields that were set in the constructor, without the need for synchronization.

This made me confuse that the set to aMap is aMap = new HashMap();. So other threads can see these

aMap.put("1", "a");

aMap.put("2", "b");

aMap.put("3", "c");

or not ?

Edit: I found this question that exactly closed to my question

解决方案

As already pointed out it's absolutely thread-safe, and final is important here due to its memory visibility effects.

Presence of final guarantees that other threads would see values in the map after constructor finished without any external synchronization. Without final it cannot be guaranteed in all cases, and you would need to use safe publication idioms when making newly constructed object available to other threads, namely (from Java Concurrency in Practice):

Initializing an object reference from a static initializer;

Storing a reference to it into a volatile field or AtomicReference;

Storing a reference to it into a final field of a properly constructed object; or

Storing a reference to it into a field that is properly guarded by a lock.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值