Home | History | Annotate | Download | only in mockref
      1 /*
      2  * Copyright (c) 2018 Mockito contributors
      3  * This program is made available under the terms of the MIT License.
      4  */
      5 
      6 package org.mockito.internal.invocation.mockref;
      7 
      8 import java.io.ObjectStreamException;
      9 import java.lang.ref.WeakReference;
     10 
     11 /**
     12  * A weak reference that is converted into a strong reference when serialized.
     13  * See {@link MockReference}.
     14  */
     15 public class MockWeakReference<T> implements MockReference<T> {
     16 
     17     private final WeakReference<T> ref;
     18 
     19     public MockWeakReference(T t) {
     20         this.ref = new WeakReference<T>(t);
     21     }
     22 
     23     private Object writeReplace() throws ObjectStreamException {
     24         return new MockStrongReference<T>(get(), true);
     25     }
     26 
     27     @Override
     28     public T get() {
     29         T ref = this.ref.get();
     30 
     31         if (ref == null) {
     32             throw new IllegalStateException("The mock object was garbage collected. " +
     33                 "This should not happen in normal circumstances when using public API. " +
     34                 "Typically, the test class keeps strong reference to the mock object " +
     35                 "and it prevents getting the mock collected. Mockito internally needs " +
     36                 "to keep weak references to mock objects to avoid memory leaks for " +
     37                 "certain types of MockMaker implementations. If you see this exception " +
     38                 "using Mockito public API, please file a bug. For more information see " +
     39                 "issue #1313.");
     40         }
     41 
     42         return ref;
     43     }
     44 }
     45