my dog learned polymorphism
The moose likes Servlets and the fly likes Listeners in a cluster 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 » Servlets
Bookmark "Listeners in a cluster" Watch "Listeners in a cluster" New topic

Listeners in a cluster

Luc Russell

Joined: Feb 09, 2004
Posts: 2
I have a web application with a ServletContextListener which starts a timer in the contextInitialised method in order to run a scheduled batch process. This works fine in a single server situation, but when the application is deployed in a cluster, the listener is instantiated once for each server, so the process is run more than once. I'd be most grateful if anyone has any suggestions on how to handle this - so far the only thing I can think of is to add a flag into the session when the timer is created, so it only happens once (am I right in believing the HTTPSession applies across all the instances in a cluster?).
Jeanne Boyarsky
author & internet detective

Joined: May 26, 2003
Posts: 33134

The HttpSession is shared across instances (it is really serialized, but it acts as one.) The problem is that there is one HttpSession per user. Do you want one batch job per user or one batch job in general?
You could use an external file as a flag if the cluster is one box. Also, you could deploy the timer for the batch job as a separate web app and only deploy it to one machine in the cluster.

[OCA 8 book] [Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Other Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, TOGAF part 1 and part 2
Luc Russell

Joined: Feb 09, 2004
Posts: 2
Thanks very much for these comments; in the end, getting access to the session was going to be a bit of a problem from the listener class itself, so instead I used the JNDI context to hold a 'lock' flag (not something I'd tried before). In the EJB method which is called by the listener, I use something like this to check for the presence of a lock, and only start the process if one is not registered:
try {
ctx = new InitialContext();
Boolean b = (Boolean)ctx.lookup(TRIGGER);
} catch (NamingException e) {"Process has not yet been started, starting now");
ctx.bind(TRIGGER,new Boolean(true));
Then at the end of the method, the lock is cleared. When multiple timers exist and fire notifications at the same time, the process will not trigger, if a lock is registered. This seems to do the job, but please let me know if you see any problems with this approach!
I agree. Here's the link:
subject: Listeners in a cluster
It's not a secret anymore!