Note that there are some explanatory texts on larger screens.

plurals
  1. POCustom equals/hash when inserting key (Guava Cache)
    primarykey
    data
    text
    <p>Simply, I have to override the way in which the cache chooses the right key because some fields (e.g., timestamp, message id, etc.) shouldn't be considered when retrieving a key. <strong>I cannot modify the actual hash function</strong> of the key object because it is already used to recognize in my code. <br> Is it possibile with Guava Caches? And with a workaround? <br><br> This is my configuration:</p> <pre><code>CacheBuilder.newBuilder().maximumSize(CACHE_SIZE).recordStats(). expireAfterWrite(DEFAULT_AGE, TimeUnit.DAYS).build( new CacheLoader&lt;Request, Response&gt;() { @Override public Response load(Request request) { return request.getResponse(); } }); </code></pre> <p>And this is my hash function (used somewhere else in my code):</p> <pre><code>public int hashCode() { final int prime = 31; int result = 1; result = prime * result + code; result = prime * result + messageID; // &lt;= **this one shouldn't evaluated** result = prime * result + Arrays.hashCode(payload); result = prime * result + (int) (timestamp ^ timestamp &gt;&gt;&gt; 32); // &lt;= **this one shouldn't evaluated** result = prime * result + (type == null ? 0 : type.hashCode()); result = prime * result + version; return result; } </code></pre> <p>Btw, is this kind of cache using its own implementation of hash function (e.g., through introspection) or is it using the default one? <br><br> ** <strong>EDIT:</strong> ** <br> As pointed out in the responses, the best way to achieve this result is a wrapper class.<br> <strong>My solution</strong>:</p> <pre><code>/** * Nested class to store a request as a key in the cache. It is needed to * normalize the variable fields of the normal requests. */ private static final class CachedRequest extends Request { private static CachedRequest fromRequest(Request request) { // set only the fields that cannot change between two same requests // ... } @Override public int hashCode() { HashFunction hashFunction = Hashing.md5(); HashCode hashCode; // ... return hashCode.asInt(); } @Override public boolean equals(Object obj) { // coherent with hashCode() // ... } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload