diff --git a/lib/java/persistance/src/main/java/org/enso/persist/PerGenerator.java b/lib/java/persistance/src/main/java/org/enso/persist/PerGenerator.java index aceebece524c..22cb24e88b9f 100644 --- a/lib/java/persistance/src/main/java/org/enso/persist/PerGenerator.java +++ b/lib/java/persistance/src/main/java/org/enso/persist/PerGenerator.java @@ -15,6 +15,7 @@ final class PerGenerator { static final byte[] HEADER = new byte[] {0x0a, 0x0d, 0x03, 0x0f}; private final OutputStream main; private final Map knownObjects = new IdentityHashMap<>(); + private final Map enteredObjects = new IdentityHashMap<>(); private final Histogram histogram; private final PerMap map; final Function writeReplace; @@ -59,6 +60,9 @@ final int writeObject(T t) throws IOException { java.lang.Object obj = writeReplace.apply(t); java.lang.Integer found = knownObjects.get(obj); if (found == null) { + if (enteredObjects.put(obj, 0) != null) { + throw new IllegalStateException("Cyclic reference detected"); + } org.enso.persist.Persistance p = map.forType(obj.getClass()); java.io.ByteArrayOutputStream os = new ByteArrayOutputStream(); p.writeInline(obj, new ReferenceOutput(this, os)); @@ -83,6 +87,10 @@ final void writeIndirect(Object obj, Persistance.Output out) throws IOException } java.lang.Integer found = knownObjects.get(obj); if (found == null) { + if (enteredObjects.put(obj, 0) != null) { + throw new IllegalStateException("Cyclic reference detected"); + } + var os = new ByteArrayOutputStream(); var osData = new ReferenceOutput(this, os); p.writeInline(obj, osData);