2

I'm having one application which fires the same query again and again on every page request coming from the browser. so I want to cache that query result from first time request triggered ,which results in an arraylist, so that on every request coming from browser ,It should not fire the same query again and again.

can you please share your thoughts or inputs ?

Edit:

Frameworks : I'm using ibatis framework for database query and struts with displaytag for UI

Here is the snippet of code :

if (req.getParameter("d-2464500-p") == null) {
    UserService userService = UserServiceFactory.getUserService();
    long startTime1 = System.nanoTime();
    log.info("start time is :" + startTime1);
    userList = userService.getUserList();
} else {
    // I want to use the same queried userList for the other pages
    // so that i should not go and fire the query
}
djm.im
  • 3,295
  • 4
  • 30
  • 45
Deepak Jain
  • 305
  • 1
  • 3
  • 19
  • Are you using any particular framework? That will influence the kind of solution you can use. Are you caching a database query or a call to another service? Some more detail and a code sample would be helptful. – Matt Watson Apr 26 '17 at 14:20
  • @MattWatson I'm using ibatis framework for database query and struts with displaytag for UI. I'm querying once for the first page and want to keep that arraylist cached or anything like similar so that i dont query again for the same arraylist on other pages. – Deepak Jain Apr 26 '17 at 14:24
  • You should add that information to the question then - along with your code. It will make it much more likely for someone who knows about those frameworks to answer your question. – Matt Watson Apr 26 '17 at 14:26
  • @MattWatson I was not much sure whether i should post the frameworks info and code or not for this type of question so only I didn't – Deepak Jain Apr 26 '17 at 14:35
  • @MattWatson I've updated the question with those things – Deepak Jain Apr 26 '17 at 14:35

1 Answers1

1

Why not lazy-loading? Something like this:

private List<?> userList = null;

private List<?> getUserList() {
    if(this.userList == null) {
        UserService userService = UserServiceFactory.getUserService();
        long startTime1 = System.nanoTime();
        log.info("start time is :" + startTime1);
        userList = userService.getUserList();
    }
    return userList;
}

and use the getUserList() method to obtain your users.

  • 1
    This will work if list doesn't get changed. If i have to add anything or remove it won't reflect on UI until and unless we don't restart the server. I'm having an option of edit, remove and add new user so this won't work – Deepak Jain Apr 27 '17 at 05:42
  • 1
    In that case I advise you to take a look at a third party caching framework. Ehcache is great. [www.ehcache.org](http://www.ehcache.org/) –  Apr 27 '17 at 10:13
  • Yeah that would be great. – Deepak Jain Apr 27 '17 at 10:40