tutorials
tutorials copied to clipboard
Lock striping Java code might be flawed
It looks the Java code in the article https://www.baeldung.com/java-lock-stripping (respectively this directory of the repository) might be flawed:
- The name of the parameter
int threadsis misleading. The code usesCompletableFuture.supplyAsync(Supplier)which uses the common pool with a fixed number of threads. The parameterthreadsis rather a task count divided by 4. - The usage of
StripedwithHashMapdoes not appear to be thread-safe.HashMapis in general not thread-safe; trying to lock only certain areas of it with a striped lock can most likely not be thread-safe because even if two entries were placed in separate buckets, the map also has global state such as the total map size which has to be accessed in a thread-safe way. Besides that, it is unlikely that the current usage of the striped lock really matches howHashMapdistributes the entries, especially when the map is rehashed when the capacity is increased during addition of new entries. - The comparison is done with a
ConcurrentHashMapwith additional synchronization. The experiment and benchmarking code seems to apply the locks toConcurrentHashMapas well. This usage is rather weird and probably not close to reality because it is unlikely that one puts additional synchronization aroundConcurrentHashMapusage. Instead it might be more interesting to see comparison between a striped lock implementation and directConcurrentHashMapusage (without any additional synchronization on it).
The idea of showcasing how Guava's Striped can be used and comparing it with another concurrent collection is really great, but for that HashMap should probably not be used due to the issues outlined above.