smeeb
smeeb

Reputation: 29577

Guava cache for custom POJO

I am trying to get Guava Caching working for my app. Specifically, I'm basically looking for a cache that behaves like a map:

// Here the keys are the User.getId() and the values are the respective User.
Map<Long, User> userCache = new HashMap<Long, User>();

From various online sources (docs, blogs, articles, etc.):

// My POJO.
public class User {
    Long id;
    String name;
    // Lots of other properties.
}

public class UserCache {
    LoadingCache _cache;
    UserCacheLoader loader;
    UserCacheRemovalListener listener;

    UserCache() {
        super();

        this._cache = CacheBuilder.newBuilder()
            .maximumSize(1000)
            .expireAfterAccess(30, TimeUnit.SECONDS)
            .removalListener(listener)
            .build(loader);
    }

    User load(Long id) {
        _cache.get(id);
    }
}

class UserCacheLoader extends CacheLoader {
    @Override
    public Object load(Object key) throws Exception {
        // ???
        return null;
    }
}

class UserCacheRemovalListener implements RemovalListener<String, String>{
    @Override
    public void onRemoval(RemovalNotification<String, String> notification) {
        System.out.println("User with ID of " + notification.getKey() + " was removed from the cache.");
    }
}

But I'm not sure how/where to specify that keys should be Long types, and cached values should be User instances. I'm also looking to implement a store(User) (basically a Map#put(K,V)) method as well as a getKeys() method that returns all the Long keys in the cache. Any ideas as to where I'm going awry?

Upvotes: 0

Views: 859

Answers (2)

andreGree
andreGree

Reputation: 1

You can (and should!) not only specify the return type of the overriden load method of CacheLoader to be User but also the onRemoval method argument to be:

class UserCacheRemovalListener implements RemovalListener<String, String>{
@Override
public void onRemoval(RemovalNotification<Long, User> notification) {
   // ...
}

}

Upvotes: 0

Louis Wasserman
Louis Wasserman

Reputation: 198581

Use generics:

class UserCacheLoader extends CacheLoader<Long, User> {
    @Override
    public User load(Long key) throws Exception {
        // ???
    }
}

store(User) can be implemented with Cache.put, just like you'd expect.

getKeys() can be implemented with cache.asMap().keySet().

Upvotes: 1

Related Questions