• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

static variables in EJB bean

 
Wai Hung
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
EJB are supposed to write as single-threaded process, so can I declare static variable in EJB?
Do I need to use 'synchronized' when I update the static variable?
 
Avi Abrami
Ranch Hand
Posts: 1141
1
Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Wai,
The EJB specifications warns against using mutable static members in EJB implementation classes because EJB containers may use several, different class loaders. A class static member is only "static" in a single class loaders. If your EJB container only uses a single class loader for all its EJB instances, then you can safely use a mutable static member -- but your EJB may not be portable (but portability may not be an issue for you :-)

Good Luck,
Avi.
 
Alex Sharkoff
Ranch Hand
Posts: 209
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just adding to Avi's comments...

That is what the spec says (section 24.1.2 Programming restrictions)

� An enterprise Bean must not use read/write static fields. Using read-only static fields is allowed. Therefore, it is recommended that all static fields in the enterprise bean class be declared as final.
This rule is required to ensure consistent runtime semantics because while some EJB Containers may use a single JVM to execute all enterprise bean�s instances, others may distribute the instances across multiple JVMs.


 
Pradeep bhatt
Ranch Hand
Posts: 8933
Firefox Browser Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Using static variables does not work in clustered environments.
 
Mo Gupta
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I agree with above 2 comments, Clusterring and VM's in use are to be considered.
If coding is still under some assumptions values can be configured as params and manage the scope of variable to which it is assigned.
- Manoj.
 
somkiat puisungnoen
Ranch Hand
Posts: 1312
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you can read static variable with final.

Example static final int test = 0;
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic