This week's giveaway is in the EJB and other Java EE Technologies forum. We're giving away four copies of EJB 3 in Action and have Debu Panda, Reza Rahman, Ryan Cuprak, and Michael Remijan on-line! See this thread for details.
I have a database table filled with configuration stuff. It�s a key/value table, that maps to a java.util.Map in runtime. The thing is, I can�t afford a database hit every time a servlet/EJB needs a configuration value. But I need the latest value of the configuration (if someone updates the table, I need the value updated eventually, that is, after 1 minute or so).
The application I�m developing is a 20 consumer/minute commerce site using BEA Portal 8.1.6. The application is clustered (distributed on 3 servers).
The configuration table would be updated up to 10 times a week.
I was thinking of a simple cache architecture: 1) A ContextListener that loads the config table and set the values on a singleton SystemConfiguration object. This object is stored as a application attribute that could be retrieved by any servlet/EJB of this application. 2) A page especially designed to maintain the system configuration (CRUD) would update the table and the SystemConfiguration instance with the updated values. That way the other servlets/EJBs whould already have the latest values. 3) To maintain the other machines updated (remember, it�s clustered) the ContextListener that initially populated the SystemConfiguration object would start a thread that would every minute update the SystemConfiguration with the last configuration data of the database table, in case of changes.
Does anyone see any problem here? Is there a thread problem in updating a Map object that is used by other objects? This object would be updated by only one thread at a time, but with no synchronization control over who�s reading the data. If the data consumer threads get old data sometimes, is not a big problem.
That�s it, any comments? [ February 15, 2007: Message edited by: bengt hammarlund ]
<b><i>Bengt Hammarlund</i><br />� Sun Certified Java Programmer</b>
ServletContext is accessible per web app. If some time down the road you want to use this config data for other web apps on the same engine, you may end up with a different approach. Could you store the config data under JNDI environment? Look around to see whether your cluster supports cache. To avoid synchronizing the map just for reading , you can create an immutable map, allow readers to read the map. If the original map has been modified, create another immutable map in a sync block.