Java Code Geeks

Saturday, November 22, 2008

Cache vs Pool, when and why?

Cache and Pool both are very related topics in J2EE world. We use these techniques to improve performance. For example, we try to Pool the JDBC connection as opening a Database connection is costly. Similarly we Cache data in the form of objects in memory to reduce the "round-trip" time across network.
Note the way we used Pooling at one place but Caching in another place. Question is when we pool and when we cache ? We do Pooling when the objects we pool have no state in them. We do Caching when objects have states. For example, any JDBC connection object will be sufficient for the application to connect to the database. It does not matter which one is giving you the service. Hence we Pool them. But in another case, when we are looking for objects from database, lets say we have read the Customer information from database and stored them in the forms of objects in memory, in this case, we do not want any Customer object to see but we want a specific customer object whose customer id is X or whose name is 'XYZ Inc'. So the easier way to remember is - stateless information can be pooled and stateful information needs to be cached.

No comments: