It's not a secret anymore!
The moose likes EJB and other Java EE Technologies and the fly likes static variables in EJB bean Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » EJB and other Java EE Technologies
Bookmark "static variables in EJB bean" Watch "static variables in EJB bean" New topic

static variables in EJB bean

Wai Hung

Joined: Apr 15, 2004
Posts: 23
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

Joined: Oct 11, 2000
Posts: 1141

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,
Alex Sharkoff
Ranch Hand

Joined: Apr 11, 2004
Posts: 209
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.

Alex (SCJP 1.4, SCBCD 1.3, SCWCD 1.4, SCJD 1.4)
Pradeep bhatt
Ranch Hand

Joined: Feb 27, 2002
Posts: 8927

Using static variables does not work in clustered environments.

Mo Gupta

Joined: Feb 07, 2002
Posts: 10
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.

Wise thought not always comes to Wise, but Wise thinks for all thoughts.
somkiat puisungnoen
Ranch Hand

Joined: Jul 04, 2003
Posts: 1312
you can read static variable with final.

Example static final int test = 0;

Java Developer, Thailand
I agree. Here's the link:
subject: static variables in EJB bean
It's not a secret anymore!