Debugging RAM – Part 1: Java Garbage Collection – Java Heap Deep Dive

There are many excellent articles on Java Garbage Collection, Java Memory usage, and generally Java heap. Unfortunately, they are all over the place. They mix architecture, concepts, and problem solving as separate pieces. A lot of the material is out of date or doesn't include pragmatic information for solving problems with the garbage collector. E.g., pause times, heap space usage, etc.

In this post, I won't go into memory leaks. They're important but this is a different subject I would like to discuss in a post on its own. 

Lambdas for Concurrent Maps

The package java.util.concurrent contains two concurrent maps, the class ConcurrentHashMap, and the class ConcurrentSkipListMap. Both classes are thread-safe and high performant. But using them is error-prone because of reading modify write race conditions. Here come lambda expressions into the play. Lambda expressions help us to avoid these race conditions elegantly.

Let us see how.

ConcurrentHashMap: Call Only One Method Per Key

Each method of ConcurrentHashMap is thread-safe. But calling multiple methods from ConcurrentHashMap for the same key leads to race conditions. And calling the same method from ConcurrentHashMap recursively for different keys leads to deadlocks.

Let us look at an example to see why this happens: