• Post Reply Bookmark Topic Watch Topic
  • New Topic

EJB instance variables

 
Paul Hunnisett
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is it safe to use instance variables in EJB - stateless or otherwise? When beans are returned to the pools do their properties get 'reset'? Is there a lifecycle method I could use for this purpose if not?
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 35719
412
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Paul,
Welcome to JavaRanch!

It depends on what is in the instance variables. If it is immutable/references to classes without interfaces (for mocking), it is fine. If it is data you rely on, it is dangerous because you don't know what state it will be in later.
 
Paul Hunnisett
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks - that's pretty much what I thought. Which makes me wonder what the point of the @EJB annotation is... As far as Ican see it can only be used for variables at instance level in either EJBs or Servlets; which, in both cases, is dangerous...

What am I missing here?
 
Paul Hunnisett
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
http://java.sun.com/javaee/5/docs/tutorial/doc/bnbly.html

Leads me to believe that it should be safe to use instance variables in a Stateful EJB...
 
Krum Bakalsky
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You should introduce yourself with the life cycle of stateless/stateful bean instances.

For stateless beans:
Using directly instance variables is risky, since after business method execution, the bean instance goes back to the pool, and the EJB container is not required to keep its state in the sense that the next business method execution of the same bean class could be served by a totally different instance! As a rule, you should never rely on such state!

Using instance variables that are resource references (@EJB, @Resource, @PersistenceContext, @PersistenceUnit) is safe, since before a business method execution takes place, the EJB container takes the care to resolve those references on the chosen instance.
 
Paul Hunnisett
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Krum Bakalsky wrote:
Using instance variables that are resource references (@EJB, @Resource, @PersistenceContext, @PersistenceUnit) is safe, since before a business method execution takes place, the EJB container takes the care to resolve those references on the chosen instance.


Thank you! That's what I was hoping was the case. I spent ages googling the lifecycle of EJBs but found limited stuff and none that answered my questions about annotations.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!