I was reading this blog and played with the suite that tests how fast read/writes to a long are and I came across a class new to JDK 1.8, LongAdder.
(The test suite has a problem that the class that uses optimistic locking and a StampedLock ignores whether it has attained the lock but I'll deal with that elsewhere).
It's quite a cunning idea. If there is contention on the field containing the long value, the thread that fails to attain the lock creates a new memory location (a Striped64.Cell object) and adds its values there. When it comes to seeing the results of many threads mutating the value, the reader thread returns not just the base value but all values in the additional memory. Thus contention is minimized.
There is a caveat when it comes to adding up all the additional values. From the JavaDoc:
The returned value is NOT an atomic snapshot; invocation in the absence of concurrent updates returns an accurate result, but concurrent updates that occur while the sum is being calculated might not be incorporated.
Anyway, I updated the suite mentioned above adding a modified optimistic locking class that retries in the event not attaining the lock (OPTIMISTIC_CORRECT in the diagram below). The logs output look like this:
data <- read.csv("/home/henryp/Code/R/JavaLocks/firstPastPost1W15R.csv")
groupBy <- list(data$name, data$threads)
aggregatedSds <- aggregate(data,
meansAndSds <- cbind(aggregatedMeans[,c(1,5)],
ordered <- meansAndSds[order(meansAndSds[,2]),]
rownames.force = NA),
main="10000000 reads of a montonically incrementing long",
xticks="1 writer, 15 readers",
The means and standard deviations look like this:
Group.1 duration aggregatedSds[, 5]
3 DIRTY 211.9 11.95780
2 ATOMIC 594.2 71.89777
9 VOLATILE 641.0 72.22188
1 ADDER 708.7 73.71122
5 OPTIMISTIC_CORRECT 1379.3 141.92334
4 OPTIMISTIC 7518.0 1392.87967
8 SYNCHRONIZED 8682.4 1507.51283
6 RWLOCK 10515.4 665.83251
7 STAMPED 21859.3 5076.10047
Note: this has one writing thread and 15 reading threads on a 16 core (using hyperthreading) CPU. DIRTY means there was no locking, the fastest but least accurate technique. Duration (the vertical axis) is in milliseconds. I don't know why this axis is not labelled when I save the image as it is displayed in RStudio.
So, ADDER is indeed fast but not as fast as ATOMIC (which is also more accurate) on this computer and with this read/write profile. I'll try other numbers of readers and writers later.