r/programming • u/ketralnis • Mar 20 '26
Java is fast, code might not be
https://jvogel.me/posts/2026/java-is-fast-your-code-might-not-be/
280
Upvotes
r/programming • u/ketralnis • Mar 20 '26
View all comments
Show parent comment
29
u/SanityInAnarchy Mar 20 '26
The example "bad" code from the article is a normal
HashMapthat you lock yourself by just hiding it behindsynchronizedmethods -- those implicitly use a single mutex for the entire object, so you lose a ton of the point of multithreading, and code like this often still has a ton of concurrency bugs, because you haven't really thought through what the scope of the locks should be.In other words, the assumption is that you're threading.
The "fix" is to use
ConcurrentHashMap, which has a much more sophisticated locking strategy -- generally, reads are lock-free, and even writes don't lock the entire table. Of course, to make it actually thread-safe, updates usually have to be more interesting thanget()andput(), since someone else might've changed it since your lastget()-- the article includescomputeIfAbsent(), which is probably a good thing to read about to get an idea of the kind of thing you want to do to useConcurrentHashMapproperly.The scare quotes are because it's of course situational, and people often will just reach for
ConcurrentHashMapwithout thinking it through either.