Class ByteBuddyCrossClassLoaderSerializationSupport

    • Field Detail

      • MOCKITO_PROXY_MARKER

        private static final java.lang.String MOCKITO_PROXY_MARKER
        See Also:
        Constant Field Values
      • instanceLocalCurrentlySerializingFlag

        private boolean instanceLocalCurrentlySerializingFlag
      • mutex

        private final java.util.concurrent.locks.Lock mutex
    • Constructor Detail

      • ByteBuddyCrossClassLoaderSerializationSupport

        ByteBuddyCrossClassLoaderSerializationSupport()
    • Method Detail

      • writeReplace

        public java.lang.Object writeReplace​(java.lang.Object mockitoMock)
                                      throws java.io.ObjectStreamException
        Custom implementation of the writeReplace method for serialization.

        Here's how it's working and why :

        1. When first entering in this method, it's because some is serializing the mock, with some code like :

          
           objectOutputStream.writeObject(mock);
           

          So, ObjectOutputStream will track the writeReplace method in the instance and execute it, which is wanted to replace the mock by another type that will encapsulate the actual mock. At this point, the code will return an ByteBuddyCrossClassLoaderSerializationSupport.CrossClassLoaderSerializableMock.

        2. Now, in the constructor CrossClassLoaderSerializationProxy(java.lang.Object) the mock is being serialized in a custom way (using ByteBuddyCrossClassLoaderSerializationSupport.MockitoMockObjectOutputStream) to a byte array. So basically it means the code is performing double nested serialization of the passed mockitoMock.

          However the ObjectOutputStream will still detect the custom writeReplace and execute it. (For that matter disabling replacement via ObjectOutputStream.enableReplaceObject(boolean) doesn't disable the writeReplace call, but just just toggle replacement in the written stream, writeReplace is always called by ObjectOutputStream.)

          In order to avoid this recursion, obviously leading to a StackOverflowError, this method is using a flag that marks the mock as already being replaced, and then shouldn't replace itself again. This flag is local to this class, which means the flag of this class unfortunately needs to be protected against concurrent access, hence the reentrant lock.

        Parameters:
        mockitoMock - The Mockito mock to be serialized.
        Returns:
        A wrapper (ByteBuddyCrossClassLoaderSerializationSupport.CrossClassLoaderSerializationProxy) to be serialized by the calling ObjectOutputStream.
        Throws:
        java.io.ObjectStreamException
      • mockReplacementCompleted

        private void mockReplacementCompleted()
      • mockReplacementStarted

        private void mockReplacementStarted()
      • mockIsCurrentlyBeingReplaced

        private boolean mockIsCurrentlyBeingReplaced()