Static Data Members In EJB


EJB design: Static Data Members In EJB

  1. Static Data Members In EJB (2 messages)

    In plain old J2SE, as you know, static members of a class represent data that are not unique to any particular instance of the class and instead hold "classwide" information. My question then is a simple one......moving to J2EE, can a bean class contain static data members? I don't see why not offhand, but there could be an issue regarding the way bean instances are created (with Class.newInstance()). Moreover, there could also be an issue when passivating a bean instance. I have been told that the J2EE specification expressly prohibits static data members in bean classes. Could someone please give me any insights they have to offer? Thanks so much.
  2. Static Data Members In EJB[ Go to top ]

    First of all, a general advise that I have found very usefull. Don't rely on "rumors" about what the EJB spec sais. The EJB spec is a normative document. You must pay attention to the exact wording of the rules. When rumors about the spec go around they tend to drop the details and turn into very general statements, like "EJBs can't use" or "EJBs can't use static fields", which are really not accurate.

    First let's see what the EJB spec sais:
    "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 restriction is in order to make sure two seperate EJBs do not "interact" with each other through static fields. This can lead to inconsistent behaiviour in different AppServers (according to the class loading strategy, clustering, etc.). Unless you do this kind of "interaction", there shouldn't be a problem.
    In some cases you do want to cause this kind of interaction, for instance for caching. When you do that kind of thing, you are in grey territory. There shouldn't generally be a problem (if you are aware of the inconsistency in different AppServers) but your code is not 100% portable. In these cases, I would think twice about whether or not it is worth the risk, as small as it may be.

  3. Static Data Members In EJB[ Go to top ]

    Nice response! I think this also goes back to the Singleton discussion in the same group.

    Basically, you can have read-only global attributes, as these are simply replicated by objects on multiple machines. Reading these attributes you can pick an object at random and get a consistent read. Not a problem.

    However, if you want to have editable global vars (singletons, static vars, etc.), you can't rely on the distributed objects, as some objects will ALWAYS go out of sync (unless you can devise a method to update the whole collection of objects on separate machines as a single transaction... not an easy task!)

    If you have a global variable you need to keep track of, I'd suggest an age-old solution -- a good RDBMS. :-)