Using Guava’s MapMaker

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

1. Introduction

MapMaker is a builder class in Guava that makes it easy to create thread-safe maps.

Java already supports WeakHashMap to use Weak References for the keys. But, there is no out-of-the-box solution to use the same for the values. Luckily, MapMaker provides simple builder methods to use WeakReference for both the keys and the values.

In this tutorial, let's see how MapMaker makes it easy to create multiple maps and to use weak references.

3.4. Using Weak References

The maps we created above use strong references for both the keys and values. So, the entries stay in the map even if the keys and the values are garbage-collected. We should use weak references instead.

A sessionCache entry is invalid after the key (the user object) is garbage-collected. So, let's use weak references for the keys:

When these references are garbage-collected, Guava guarantees that these entries will not be included in any of the subsequent read or write operations on the map. However, the size() method might sometimes be inconsistent and can include these entries.

4. MapMaker Internals

MapMaker creates a ConcurrentHashMap by default if weak references are not enabled. The equality checks happen via the usual equals method.

If we enable weak references, then MapMaker creates a custom map represented by a set of hash tables internally. It also shares similar performance characteristics as a ConcurrentHashMap.

However, an important difference with WeakHashMap is that the equality checks happen via the identity (== and identityHashCode) comparisons.

5. Conclusion

In this short article, we learned how to use the MapMaker class to create a thread-safe map. We also saw how to customize the map to use weak references.

As always, the full source code of the article is available over on GitHub.

Generic bottom

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2: