forked from guanpengchn/java-concurrent-programming
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPoint.java
More file actions
33 lines (29 loc) · 807 Bytes
/
Copy pathPoint.java
File metadata and controls
33 lines (29 loc) · 807 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package ch6.s6;
import java.util.concurrent.locks.StampedLock;
public class Point {
private double x,y;
private final StampedLock s1 = new StampedLock();
void move(double deltaX, double deltaY){
long stamp = s1.writeLock();
try{
x += deltaX;
y += deltaY;
} finally {
s1.unlockWrite(stamp);
}
}
double distanceFromOrigin(){
long stamp = s1.tryOptimisticRead();
double currentX = x, currentY = y;
if(!s1.validate(stamp)){
stamp = s1.readLock();
try{
currentX = x;
currentY = y;
} finally {
s1.unlockRead(stamp);
}
}
return Math.sqrt(currentX*currentX + currentY*currentY);
}
}