Skip to content
Robert edited this page Feb 11, 2016 · 4 revisions

All scopes can be used to return either a concrete object, or a Supplier. As there are no transparent proxies, or other magical mechanisms employed, objects that are directly returned are serializable if the object itself is serializable. Please note, that if a singleton object is used directly (without a Supplier), then a deserialization will produce a new instance every time.

All the standard scopes support serializable Supplier objects however. These will keep all guarantees of the scope that produced it, and are serializable even if the supplied objects are not.

Serializable Suppliers

When using suppliers from any of the standard scopes this way:

public Supplier<SomeService> getSomeServiceSupplier() {
   return sessionScope( () -> new SomeService(...) );
}

Then these returned Supplier objects will be serializable, even if SomeService is not.

Serialization details

Serialization of suppliers is achieved by serializing the Factory objects that created them. These Factory objects are usually created by lambda expressions and may have references to the module object, since they directly call instance methods to get dependencies. Consider the following:

public class MyAppModule extends StandaloneModule implements ProxySupport {
    ...
    public Proxy<Connection> getConnectionProxy() {
       return autoCloseProxy(getConnectionSupplier());
    }


    public Supplier<BookRepository> getBookRepositorySupplier() {
       return getSingletonScope().apply( () -> new BookRepository(getConnectionProxy()) );
    }

    ...
}

When/if the Supplier<BookRepository> is serialized, the BookRepository object will not be serialized over the wire. Instead, the factory, which is the lambda expression in the apply() method, will be serialized. This means, it does not serialize the object, but the code to be able to get the object when deserializing. This factory however has a reference on getConnectionProxy() instance method, and with that it also has to keep a reference on MyAppModule.

This MyAppModule will not be serialized together with the Supplier however. During deserialization, which can occur in the same or in a different JVM, a static instance of a MyAppModule needs to be found to be able to complete the deserialization process. The StandaloneModule by default make a static instance from itself available, if there was one, and only one instance previously created. This logic can be modified by overriding the getStaticDeserializationModule() method, for example to make your module a static singleton:

public class MyAppModule extends StandaloneModule {
   private static final MyAppModule INSTANCE = new MyAppModule();

   private MyAppModule() {
   }

   public static MyAppModule getInstance() {
      return INSTANCE;
   }

   ...
   @Override
   protected Object getStaticDeserializationModule() {
      return INSTANCE;
   }
   ...

Clone this wiki locally