Java – how do you ensure that multiple threads can safely access class fields?
How do you maintain thread safety when accessing class fields through getter methods through multiple threads? Is the synchronization keyword sufficient?
Is this safe?
public class SomeClass { private int val; public synchronized int getVal() { return val; } private void setVal(int val) { this.val = val; } }@H_419_5@或者是否引入更多的并发症?
Solution
If 'synchronized' is also used on the setter here, this code is thread safe However, it may not be granular enough; If you have 20 getters and setters and they are synchronized, you may create a synchronization bottleneck
In this specific example, using a single int variable, then eliminating 'synchronized' and marking the int field 'volatile' will also ensure visibility (each thread will see the latest 'Val' value when calling getter), but it may not be synchronized according to your needs For example, expectations
int old = someThing.getVal(); if (old == 1) { someThing.setVal(2); }@H_419_5@将val设置为2,如果且仅当它已经是1是不正确的.为此,您需要一个外部锁定或一些原子比较和设置方法.
我强烈建议您阅读Brian Goetz等人的Java并发实践,它具有Java并发结构的最佳覆盖.