5

The javadoc as well as this question both emphasize on

Enum sets are represented internally as bit vectors.

Now I am wondering - what is the behaviour when sending (standard Java serialized) EnumSet objects over the wire to some other JVM that might have a different version of the underlying Enum class?

In other words: when I sent some Set<MyEnum> it is very well possible that an exception is thrown during de-serialization on the other JVM (in cases where my JVM is using some MyEnum.NEW_GUY that the other JVM doesn't know about). In that situation, the deserialization tries to instantiate an enum constant that doesn't exist in the class on the other JVM.

But assuming that EnumSet doesn't transport enum constant instances (but just a bit set with some bits true, some false) - what happens when the serialized EnumSet included MyEnum.NEW_GUY?

I tried to identify a specification that tells me what should happen ( versus assuming that this is an implementation detail ), but no luck so far.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
  • _"But assuming that EnumSet doesn't transport enum constant instances"_ Looking at the source (JDK9), this is not the case. It uses a serialization proxy which saves the element type `Class` and an array of constants. – Jorn Vernee Feb 09 '18 at 13:03
  • 2
    According to the source code: The bit vector is recalculated after reading an object from a stream. The serialization only writes an array of the enum values to the stream (besides the enum class). That means you can change the order of the enum values, and you also can add new enum values as long as you don't have them serialized in the set. – Seelenvirtuose Feb 09 '18 at 13:22

1 Answers1

4

Regarding implementation only (using Oracle Java 8), the answer is: it is not "just" a bitset.

Meaning: one can quickly write a test that serializes an EnumSet instance into a file, then change the enum class, and run code that reads back the set from the file.

Turns out:

  • if the file contains an enum constant that doesn't exist any more, a java.io.InvalidObjectException: enum constant B does not exist in class com.ibm.hwmca.z.managed.TestEnum is thrown
  • if all enum constants exist, but their order is changed - the set that gets read back is still correct.

In other words: that test suggests is that a serialized EnumSet does contain "more" information than just a plain bitset. The implementation is able to A) detect "missing" enum constants and B) deal with changes to the enum class that only affect the ordering of entries. Matching up with the comments by @Seelenvirtuose that the serialized EnumSet isn't a bit vector, but an array containing actual enum constants (thus being open for the exact same version conflict).

Still searching if there is a specification for the observed behavior.

GhostCat
  • 137,827
  • 25
  • 176
  • 248