1 Reply Latest reply on Dec 26, 2007 4:18 PM by waynebaylor

    How to implement a "global" app counter?

    sagimann

      Hello,

      I'm using JBoss 4.2.2, and I have the following challenge: I have an entity that keeps track of a "global" numeric value for my application, inside the db. I need a session been that should be able to:
      1. init the counter to 0
      2. update it atomically, i.e when I call some 'getNext' method, it will return the next number and increment the counter in one go.

      Something like:

      @PersistenceContext EntityManager em;
      
      void init() {
      // internally, MyCounter's ID field is always 1. I just set the counter value to 0:
      em.persist(new MyCounter(0));
      }
      
      Long getNext() {
      // this is the challenge....
      }
      

      My question is: how do I implement such a thing in a cluster-aware application? In a non-clustered environment, I would consider creating a separate persistence unit just for this entity, which will use a db pool that serializes transactions (highest isolation level). Since the transaction is very short relative to transactions in the "normal" PU, it should have little effect on performance.

      This would simply require me to set the PU name on the session bean's 'em' member, e.g.:
      @PersistenceContext(name="serializedPU")
      EntityManager em;
      

      BUT: in a clustered environment, each appserver would have its own db pool, there is no sync between them... I was thinking of a few options to resolve this:

      1. configure all appservers in the cluster to reference a specific appserver for this specific bean, but this would create a single point of failure...

      2. Instead of using a separate PU, I could configure the session bean's pool size to max=1, and again, configure all appservers in the cluster to use this bean only on one specific appserver. And again: single point of failure...

      3. do something at the dbms level, but this will require knowledge of dbms-specific technicalities, make my application's deployment a lot more complex, etc.

      Any better/other suggestions, please?
      thanks...