In the Java Concurrency in Practice book you can find following code:
@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;
}
}
This marked as @ThreadSafe
.
I am pretty sure that this class is not thread-safe (if I understand this term correctly).
Example:
SafePoint racePublishedSafePoint; // field
// thread 1:
racePublishedSafePoint = new SafePoint(1,1);
// thread 2:
SafePoint sp;
while(true){
SafePoint sp = racePublishedSafePoint;
if(sp != null) break;
}
System.out.println(sp.get()[0]);
System.out.println(sp.get()[1]);
I believe that there is several possible outcomes:
- The application doesn't finish
else
- If application finished, we can see
a) 0 0
b) 0 1
c) 1 0
d) 1 1
Am I right?
If true, why did the author mark the class as thread safe? I thought that thread-safe class - class which can be used in concurrent application without sophisticated analysis.
What did author want to say?
P.S.
I have read the
Private constructor to avoid race condition
...and my topic is not duplicate.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…