Question

Consider a hypothetical application:

  • That has a need to create tens or even hundreds of small groups of objects
    • (Group A: Class A instance, Class D instance, Class M instance. Properties P')
    • (Group B: Class B instance, Class D instance)
    • (Group C: Class B instance, Class D instance, Class F instance. Properties P'')
  • Each of these objects are created by its own Provider that is registered with the parent/root Injector using MapBinder or MultiBinder (typical "plugin" usecase)
  • To create each group, a new child Injector is created that uses the Providers from the root and a few other providers that are local to this child Injector - like configuration/properties bindings
  • This tight group of objects is created together to perform some task and then discarded together - after a few hours
  • The group has some unique parameters
    • Meaning, that each object created within the group has distinct configuration properties
    • They are different from another instance of that class in a different group

Question: Assuming that for some reason the problem described above cannot be accomplished by using run of the mill design patterns like Factory, Builder, Creator etc:

  • Is there anything wrong with the approach described above?
    • Performance, memory foot print
    • Readability (vs using plain old Java new)
  • Does it sound too complicated and relying on libraries to do something simple?
Was it helpful?

Solution

At the level of abstraction you described, that sounds like a reasonable solution, and conducive to some good design patterns (like loose coupling and instance immutability). To the best of my knowledge Guice will not pose any greater threat of memory leaks or other performance problems than any comparable solution for those complex needs—just keep an eye on which references you keep so the GC can do its job.

To that point you may want to be careful about creating singleton objects in Guice, though, if you rely on them being garbage collected. Objects declared as @Singleton (or asEagerSingleton or toInstance) cannot be garbage-collected as long as the Injector is reachable, because the Injector is obligated to return the exact same instance if it is ever asked for again. In desktop VMs it may be cheaper to get multiple instances of a stateless object so the GC can collect them all, rather than declaring the object as a singleton that can never be collected.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top