139. Avoiding StackOverflowError at deserialization
Let’s consider the following snippet of code:
// 'mapOfSets' is the object to serialize/deserialize
HashMap<Set, Integer> mapOfSets = new HashMap<>();
Set<Set> set = new HashSet<>();
mapOfSets.put(set, 1);
set.add(set);
We plan to serialize the mapOfSets
object as follows (I assume that Converters.objectToBytes()
is well-known from the previous problems):
byte[] mapSer = Converters.objectToBytes(mapOfSets);
Everything works just fine until we try to deserialize mapSer
. At that moment, instead of a valid object, we will get a StackOverflowError
as follows:
Exception in thread "main" java.lang.StackOverflowError
at java.base/java.util.HashMap$KeyIterator
.<init>(HashMap.java:1626)
at java.base/java.util.HashMap$KeySet
.iterator(HashMap.java:991)
at java.base/java.util.HashSet
.iterator(HashSet.java:182)
at java.base/java.util.AbstractSet...