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.
SafePoint
is thread-safe. Your example code is not thread-safe. – LedererSafePoint
from multiple threads safely, whereas using 'Date` concurrently will result in the corruption of the internal state of the object. YOUR BROKEN EXAMPLE CODE DOES NOT CORRUPT THE INTERNAL STATE OFSafePoint
. IT DOES NOT SAFELY PUBLISH THE INSTANCE, SO IT'S BROKEN CODE BUT IT DOES NOT BREAKSafePoint
. – LedererDate
a thread-safe class. It just means that you're using external code to (try to) use it in a thread-safe fashion. – LedererSafePoint
. It's you who wrote the broken code, nobody else. If you write broken code, don't ask "why does this code not work correctly", since you obviously know that the code is broken (based on you naming the variableracePublishedSafePoint
). – LedererSafePoint
andString
. – LedererString
, but doesn't work withSafePoint
. Are you still blaming theSafePoint
class? – Lederer