Binu
Binu

Reputation: 120

Query Results caching using Java : Any better Approaches?

I have a class ClassA which calls another class(DAO) to fetch the query results. In a specific business scenario,

ClassA invokes the DAO with queryparameters about 20,000 times. Out of this, about 10,000 times ClassA sends same set of query parameters to DAO. Obviously Resultset will be the same and can be cached.

The following is the code I implemented.

Class A

{

.
.
.
.

Map<String, CachData> cachDataMap= new HashMap<String, CachData>();

priavate void getQueryResults(String queryParam)    
{

try {


            Set<String> cacheSet = cachDataMap.keySet();
            CachData cachData = null;
            if(!cacheSet.contains(queryParam))
            {
                dao.getResuslts((queryParam)));
                cachData = new CachData();
                cachData.setResult0(__getStringResult(0));
                cachData.setResult1(__getStringResult(1));
                cachData.setResult2(__getStringResult(2));
                cachData.setResult3(__getStringResult(3));
                cachData.setResult4(__getStringResult(4));
                cachData.setResult5(__getStringResult(5));
                cachDataMap.put(queryParam, cachData);
            }else
            {
                cachData = cachDataMap.get(queryParam);
            }



        } catch(Exception e) {
            //handle here
        }


}

Do we have anyother better solution other than using any framework? A better datastructure or better method.. For good performance?

Upvotes: 1

Views: 116

Answers (2)

bowmore
bowmore

Reputation: 11308

You could use ehcache.

Whatever you do don't use a Map as your interface for a cache. A good cache interface would allow the implementation to do cleanup of the cache. The Map contract won't allow this.

Depending on the implementation, cleanup can be based on time in the cache, or based on usage statistics, or memory availability, ...

The Map approach you're using here seems prone to go out of memory over a longer period of usage.

Upvotes: 1

Shamis Shukoor
Shamis Shukoor

Reputation: 2515

You could use the Table from guava library and use ehCache to save the object as it is with the key being the query.

Upvotes: 0

Related Questions