0

This question is to compare EJB Singleton bean and Stateless bean in the case both them are Threadsafe (No state holding OR Readonly State). I thought they can be used for the same purpose ( in case they are threadsafe). If I understand wrong, can someone let me know what are differences between them in my case? When to use which one? Thanks.

LHA
  • 9,398
  • 8
  • 46
  • 85

1 Answers1

3

Singletons maintain their state across client invocations, so there is no reason for using them to access read-only state or for no state holding processing. Common scenarios for singletons are configuration reading and/or initialization tasks at application startup or shutdown, or accessing shared resources in a thread-safe way. Moreover there is a difference in performance and scalability, singleton beans are instantiated only once and process every single request sequentially, whereas stateless beans can be pooled and can process more requests concurrently.

remigio
  • 4,101
  • 1
  • 26
  • 28
  • Thanks for your answer. "singleton beans are instantiated only once and process every single request sequentially". If mufti-threads access the singleton bean at a time, the singleton doesn't process every single request SEQUENTIALLY. Is that right? It request is processed in its own thread. – LHA Dec 05 '13 at 14:40
  • Look at the Java EE [documentation](http://docs.oracle.com/javaee/6/tutorial/doc/gipvi.html#indexterm-1449) for an explanation of the singleton thread model. Although it can be accessed in a multithreaded fashion, the default access level is `Lock.WRITE` that means that whenever a client calls a method blocks all other calling clients until the method execution finishes. – remigio Dec 05 '13 at 15:14
  • Thanks. But If Lock.READ used. The method can be concurrently accessed, or shared, with many clients. – LHA Dec 05 '13 at 15:31
  • Yes, but in that case it would be your responsibility controllling access to shared resources, and anyway there is no meaning in using singletons that way, you can just use stateless beans. – remigio Dec 05 '13 at 15:47