Best choice for Singleton replacement ?


EJB design: Best choice for Singleton replacement ?

  1. Best choice for Singleton replacement ? (1 messages)

    I have created a J2EE application (using JBoss version 3.2.6) which relies heavily on Singletons. It works well but I need to be able to cluster the application and not lose state whenever the master node which is running the Singleton goes down and the Singleton fails over to the new master node of the cluster. Unfortunately I have become aware late in the game that the Singleton pattern was not a good choice for a clustered application, due in part to the fact that once a Singleton fails over it is started from scratch on the new master node of the cluster and all of its previous state is lost. This is really causing me troubles since I need for the state of the Singletons to persist when failover occurs. From what I can tell there is no way around this problem, but I'm hoping to be able to easily hack something together in order to avoid having to significantly rewrite my code, although that might actually be simpler/better than coming up with an ugly hack.

    For example I am using a Singleton to hold user activity information. All updates go to this Singleton (last access time, last error type, etc.) and MBeans which report user activity will access this Singleton to create their reports. If this Singleton is lost and then restarted from scratch on the new master node of the cluster then bad voodoo ensues.

    In hindsight I assume that the best approach would have been to maintain this sort of information in database tables and to access it using Entity Beans or perhaps Hibernate objects.

    Can anyone comment on the best approach to this sort of problem, and what I might do, if anything, to dig myself out of this Singleton hole, short of rewriting everything using Entity Beans or Hibernate (which I assume would be the ideal solution) ?

    Thanks in advance for any suggestions.

  2. you need to save your state period[ Go to top ]

    The only way to have a singlton in a cluster is to save the data somewhere so if your box "dies" you can recreate the singleton on another box and re-add its state via a file, db, etc. You could periodically save your current state and then if you do crash you might only be slightly out of date.

    You really should move away from this model. You data a) needs to be saved and b) should not be tied to a single server. Database is perfect for this type of solution and you can use entity beans or some other mechanism. Plus reports and stuff can be generated offline, i.e. via a non-j2ee scheduler like cron if you want.