1226 |
|
for (Future<?> future : futures) |
1227 |
|
assertNull(future.get()); |
1228 |
|
} |
1229 |
+ |
|
1230 |
+ |
/** Tries out sample usage code from StampedLock javadoc. */ |
1231 |
+ |
public void testSampleUsage() throws Throwable { |
1232 |
+ |
class Point { |
1233 |
+ |
private double x, y; |
1234 |
+ |
private final StampedLock sl = new StampedLock(); |
1235 |
+ |
|
1236 |
+ |
void move(double deltaX, double deltaY) { // an exclusively locked method |
1237 |
+ |
long stamp = sl.writeLock(); |
1238 |
+ |
try { |
1239 |
+ |
x += deltaX; |
1240 |
+ |
y += deltaY; |
1241 |
+ |
} finally { |
1242 |
+ |
sl.unlockWrite(stamp); |
1243 |
+ |
} |
1244 |
+ |
} |
1245 |
+ |
|
1246 |
+ |
double distanceFromOrigin() { // A read-only method |
1247 |
+ |
double currentX, currentY; |
1248 |
+ |
long stamp = sl.tryOptimisticRead(); |
1249 |
+ |
do { |
1250 |
+ |
if (stamp == 0L) |
1251 |
+ |
stamp = sl.readLock(); |
1252 |
+ |
try { |
1253 |
+ |
// possibly racy reads |
1254 |
+ |
currentX = x; |
1255 |
+ |
currentY = y; |
1256 |
+ |
} finally { |
1257 |
+ |
stamp = sl.tryConvertToOptimisticRead(stamp); |
1258 |
+ |
} |
1259 |
+ |
} while (stamp == 0); |
1260 |
+ |
return Math.hypot(currentX, currentY); |
1261 |
+ |
} |
1262 |
+ |
} |
1263 |
+ |
|
1264 |
+ |
Point p = new Point(); |
1265 |
+ |
p.move(3.0, 4.0); |
1266 |
+ |
assertEquals(5.0, p.distanceFromOrigin()); |
1267 |
+ |
} |
1268 |
+ |
|
1269 |
|
} |