我正在阅读Java Concurrency in Practice4.3.5会议
@ThreadSafe
public class SafePoint{
@GuardedBy("this") private int x,y;
private SafePoint (int [] a) { this (a[0], a[1]); }
public SafePoint(SafePoint p) { this (p.get()); }
public SafePoint(int x, int y){
this.x = x;
this.y = y;
}
public synchronized int[] get(){
return new int[] {x,y};
}
public synchronized void set(int x, int y){
this.x = x;
this.y = y;
}
}
Run Code Online (Sandbox Code Playgroud)
我不清楚它在哪里说
私有构造函数的存在是为了避免在复制构造函数实现为此时发生的竞争条件(px,py); 这是私有构造函数捕获习惯的一个例子(Bloch和Gafter,2005).
据我所知,它提供了一个getter,可以在一个数组中同时检索x和y,而不是每个都有一个单独的getter,因此调用者将看到一致的值,但为什么是私有构造函数?这里有什么诀窍
众所周知,如果我们有一些对象引用并且此引用具有final字段 - 我们将看到来自final字段的所有可到达字段(至少在构造函数完成时)
class Foo{
private final Map map;
Foo(){
map = new HashMap();
map.put(1,"object");
}
public void bar(){
System.out.println(map.get(1));
}
}
Run Code Online (Sandbox Code Playgroud)
正如我在这种情况下所做的那样,我们保证bar()方法总是输出object因为:
1.我列出了完整的类代码,Foo并且map是final;
2.如果某个线程会看到引用Foo和引用!= null,那么我们保证从最终map引用值可以到达的是实际的.
我也是这么认为的
class Foo {
private final Map map;
private Map nonFinalMap;
Foo() {
nonFinalMap = new HashMap();
nonFinalMap.put(2, "ololo");
map = new HashMap();
map.put(1, "object");
}
public void bar() {
System.out.println(map.get(1));
}
public void bar2() {
System.out.println(nonFinalMap.get(2));
}
}
Run Code Online (Sandbox Code Playgroud)
在这里,我们对bar() …