Search code examples
javasingletoncdijava-ee-8

Should I Use CDI javax.inject.Singleton for the beans that dont need serialization, proxies, or decorations


I understand how ApplicationScoped and CDI javax.inject.Singleton work, and I understand the difference between these two scopes. My app has a lot of beans that don't need serialization, proxies, or decorations, so I am considering switching those from ApplicationScoped (which works) to javax.inject.Singleton to improve performance by avoiding proxies.

My question is: Should I in fact make such a change?


Solution

  • Of course you can do that refactoring on scope annotation, but you will need to take care of serialization on beans calling those singleton managed beans. See http://docs.jboss.org/weld/reference/latest-2.2/en-US/html_single/#_the_singleton_pseudo_scope

    I would investigate first how much performance gaining I'll get from this move and if it really worth the time I'll need to invest on it. Usually performance bottleneck comes from database query/indexing performance, I/O, network, thread-locks, inefficient algorithms (and more) before a Java proxy overhead, so I would stick to standard @ApplicationScoped.

    See: http://ordinaryjava.blogspot.com/2008/08/benchmarking-cost-of-dynamic-proxies.html https://spring.io/blog/2007/07/19/debunking-myths-proxies-impact-performance/