kryo icon indicating copy to clipboard operation
kryo copied to clipboard

The accessOrder field in LinkedHashMap is not deserialized correctly.

Open leonchen83 opened this issue 1 year ago • 1 comments

Describe the bug Since we set accessOrder to true during serialization, we expect the output order after deserialization to be a, b. However, due to the fact that the accessOrder field is not correctly deserialized, the actual output is b, a.

To Reproduce

public static void main(String[] args) {
    Kryo kryo = new Kryo();
    kryo.setReferences(true);
    kryo.setRegistrationRequired(true);
    kryo.register(LinkedHashMap.class);
    final Output output = new UnsafeOutput(512, 10240);
    
    LinkedHashMap<String, String> map = new LinkedHashMap<>(10, 0.85f, true);
    map.put("a", "a");
    map.put("b", "b");
    
    map.get("b");
    map.get("a");
    
    kryo.writeClassAndObject(output, map);
    LinkedHashMap<String, String> map1 = (LinkedHashMap) kryo.readClassAndObject(new UnsafeInput(output.toBytes()));
    
    map.get("a");
    map.get("b");
    
    for (String key : map1.keySet()) {
        System.out.println(key);
    }
}

Environment:

  • OS: windows11
  • JDK Version: 21
  • Kryo Version: 5.6.2

Additional context Add any other context about the problem here.

leonchen83 avatar Dec 23 '24 05:12 leonchen83

You are right. It is quite surprising that this has never come up before.

Kryo uses the default MapSerializer for LinkedHashMap that is completely unaware of this parameter. Your best option is to register a custom serializer that writes an additional boolean flag. See TreeMapSerializer for a serializer that extends MapSerializer with additional data.

theigl avatar Jan 07 '25 15:01 theigl