Search code examples
javalogbackthread-localmdc

Why LogbackMDC keep track of last operation?


I am looking at the implementation of LogbackMDCAdapter, and it keeps track of lastOperation I don't understand the reason for doing this, anyone has an idea why this is done?

And, why duplicateAndInsertNewMap is required?


Solution

  • Based on the comment here the map copying is required for serialization purposes

    Each time a value is added, a new instance of the map is created. This is to be certain that the serialization process will operate on the updated map and not send a reference to the old map, thus not allowing the remote logback component to see the latest changes.

    This refers to the behaviour of ObjectOutputStream sending references to previously written objects instead of the full object, unless using the writeUnshared method.

    It is not directly obvious why it's possible to skip copying unless there's a get/put combination, but apparently even if you have multiple put operations in a row, the serialization will work properly as long as the map is copied only when a put/remove is performed right after a get. So this is a performance optimization to avoid copying the map unnecessarily when putting several items in it.