|[ Team LiB ]|
Caching Objects to Reduce Setup Time
Like buffering, caching is a speed-memory tradeoff. If an item takes a long time to create and initialize, you keep it in a cache and reuse it. Database connections are excellent examples of cached resources. It takes a relatively long time to establish a database connection, so most applications create the database connections when they start up and then store the connections in a connection pool, which is another form of a cache.
Most JSP and servlet engines even come with built-in database connection pools because they are so frequently used.
The main difference between pooling and caching is that pooled objects are meant to be shared and reused. When you need a database connection, you grab it from the pool, use it, and put it back. With a cache, you typically create an object and put it somewhere for safekeeping until you need it the next time, but you don't necessarily want to share the object.
For example, when a user logs in to your application, you might query the database for information about the user. You might need this information every time the user makes a request, but you don't want to go back to the database every time to get it. Instead, you store the information in the user's session object. The session object makes an excellent cache.
In most applications, there is always some data that is pretty much read-only—for example, a list of countries or states. This is another good example of data that should be cached so that you do not have a database hit each time you need that data.
|[ Team LiB ]|