Create a HashMap key from Callable

Viewed 240

Lets say I have a callable and I want to use it as both the key and the data retriever in a cache.

Callable<SomeObject> callable = () => {
    return dataSource.getSomethingBig();
}

SomeObject result = storage.getFromCacheOrSource(callable);

Identical callables might be constructed elsewhere and be called through the cache. Thus I want to use the callable as the key in the cache to get it from there or fill the cache with the data (gotten through the callable) if it is not already in the cache.

public <T> T getFromCacheOrSource(Callable<T> callable) {
    String key = getKeyFromCallable(callable);
    if (cache.contains(key)) {
        return cache.get(key);
    }
    T data = callable.call();
    cache.put(key, data);
    return data;
}

How can I construct a key from the callable that will always be the same if the content of the callable is identical?

getKeyFromCallable(Callable<T> callable) {
     // What to do here to always return the same key for identical callables?
}
0 Answers
Related