0

I'm running guava cache for my get methods. I've noticed that one of my methods, which retrieves profile information from the database based on name and department, returns ONLY from the cache. If an entry is not in the cache, its supposed to go to the DAO to retrieve that profile from the database. In my case, its simply returning the last entry it put in the cache.

Here is my code for the cache and the manager layer method that uses it:

private LoadingCache<Profile, List<Profile>> loadingCache = CacheBuilder.newBuilder()
            .refreshAfterWrite(5, TimeUnit.MINUTES)
            .expireAfterAccess(5, TimeUnit.MINUTES)
            .maximumSize(100).build(
                    new CacheLoader<Profile, List<Profile>>() {
                        @Override
                        public List<Profile> load(Profile profile) throws Exception {
                            System.out.println("Profile Parameters in LoadCache= " + profile);
                            return profileDAO.getProfileByFields(profile);
                        }
                    }
            );

public List<Profile> getProfileByFields(Profile profile) throws Exception {
        System.out.println("Profile Parameters in method= " + profile);
        return loadingCache.get(profile);
    }

The way this works is that on the service layer, the get method is called with profile name and department in the path params:

@GET
@Path("{name}/{department}")
public List<Profile> getProfileByFieldsService(@PathParam("name") String name, @PathParam("department") String department) {
    Profile profile = new Profile();
    profile.setName(name);
    profile.setDepartment(department);
    //code to get data here.
}

Those parameters are passed to the manager, which should either load from the cache or from the DAO. I know the code the service to the DAO works properly without the cache; replacing return loadingCache.get(profile) with return profileDAO.getProfileByFields(profile) loads from the DAO as expected. Also, when I shorten the expiration on the cache (say, to 5 milliseconds), it loads from the DAO after expiring. In addition, the System.out in getProfileByFields runs, showing the parameters are passed to the profile object. However, the System out in loadingCache does not run, indicating to me that it is never reached.

SVill
  • 331
  • 5
  • 22
  • 55
  • Sounds like you might have a bad equals and hashCode() on the key – Ben Manes May 26 '18 at 16:35
  • I see what happened; when I started the project, the only method for searching for profiles was by ID number. When we expanded it to include a get method by name and department, I never updated the hashCode or equals to reflect that. Generating a new hashcode and equals seems to have fixed the problem. Thank you so much. Can you rewrite your comment as an answer so I can accept it? – SVill May 27 '18 at 18:28

0 Answers0