L. Blanc
L. Blanc

Reputation: 2310

How can i use guava cache with a byte[] key?

I created a guava cache:

Cache<byte[], byte[]>  = CacheBuilder.newBuilder()
            .maximumSize(1_000_000)
            .expireAfterAccess(20, TimeUnit.MINUTES)
            .build();use

but it doesn't find the keys when I call get(). The implementation seems to use equals() to find the key, when I need it to use Arrays.equals().

Is there anyway to set up Cache so that it works this way? Internally, it seems to have the flexibility, as the comparison uses Equivalence rather than a straight equals(), but the CacheBuilder api doesn't seem to have a way to set an Equivalence object.

Any help would be greatly appreciated.

Upvotes: 3

Views: 1375

Answers (1)

LoganMzz
LoganMzz

Reputation: 1623

If natural equality is your unique solution (like in a HashMap), just wrap your instance in an object that do the job ! JVM works very well with very short living object so don't be annoyed by creating few little objects just for cache querying.

As @LouisWasserman mentioned, you can use ByteBuffer. How ever you shoud take care to not modify array backed by cached keys.

Upvotes: 4

Related Questions