J2EE Architecture Blog

Caching in a JSF managed bean

Posted by: prowebtiger on: May 15, 2009

Some Theory …

According to wikipedia, a cache (pronounced /kæʃ/) is a collection of data duplicating original values stored elsewhere or computed earlier, where the original data is expensive to fetch (owing to longer access time) or to compute, compared to the cost of reading the cache. In other words, a cache is a temporary storage area where frequently accessed data can be stored for rapid access. Once the data is stored in the cache, it can be used in the future by accessing the cached copy rather than re-fetching or recomputing the original data.

 

Let’s get into practice…

 

Case Study:

  • I have an e-commerce site with a catalog of products stored in a relational database. When a user chooses a category, products are loaded from the database and displayed to the user.
  • Question: What if the user chooses 10 times the same category ?
  • Answer: The application will call 10 times the database querying for products of the same category resulting in a performance hit.
  • Solution : Use of caching.

Assumptions:

  • 3 tier level architecture using JSF at presentation level and EJB 3 at business level.
  • The same catalog is used for all the users.
  • A single machine is sufficient for storing the catalog. No cluster needed.
  • No need for a deletion or replacement algorithm.

Solution:

  • Create a “CachedCatalogBean” session bean that has a method “List loadCatalog()” that loads the whole catalog from the database.
  • Create an application scope JSF managed bean “CachedCatalogController” to store our catalog.
  • Define a catalog variable in the JSF maanged bean that’ll store the catalog and a getter method to access it.
  • Create a “CachedCatalogListener” that’s subclass of ServletContextListener to cache the catalog at server startup.
  • From the contextInitialized(ServletContextEvent sce) method of the “CachedCatalogListener” class, call the “loadCatalog” method to get the catalog in order to put it in the servlet context attribute “myCatalog”.
  • In the JSF managed bean constructor, get the servlet context attribute value by calling FacesContext.getCurrentInstance().getExternalContext().getContext().getAttribute(“myCatalog”) in order to initialize the JSF managed bean catalog variable that’ll be used application-wide to access our catalog.

Enjoy caching performance and have fun.

Amine.whoIs() ?

Posted by: prowebtiger on: May 15, 2009

Hi everybody. Welcome to my architecture blog. 

To introduce myself, my name’s Mohammed Amine TAZI and I was born in Morocco. I’m a senior J2EE developer and Sun Certified Enterprise Architect for JEE 5 Technology. 

I’m here to share my knowledge blogging  about architecture and development using J2EE technology.

I hope you enjoy reading and having fun.

Amine.

Follow

Get every new post delivered to your Inbox.