ThankThePhoenicians ThankThePhoenicians -3 years ago 139
Java Question

Something similar to Guava's LoadingCache, but bidirectional?

I'm working with an account system that allows users to change their display names. To accomplish this, each user has a UUID. At various points in my program, I may have a UUID and want its current display name, or I may have a current display name and I'd like to look up the UUID. Looking it up involves either a database call or http request, so I'd like to cache results in memory. I'm familiar with Guava's LoadingCache, but it seems like I'd have to create two caches (names -> UUIDs and UUIDs -> names) in order to accomplish this. This seems bug-prone, similar to how a BiMap is better than two synchronous maps Is there something similar to a bidirectional LoadingCache out there?

Answer Source

For this case, I wouldn't necessarily worry about a pair of caches being bug prone: you don't have to keep the two directions in sync, and if you fail to do so there's no real failures. UUIDs and their relationships to users aren't going to change.

Keeping a bidirectional cache correctly synchronized is difficult, but for this case it seems like overkill.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download