Is there any way to use Guava HashBiMap with eviction?

I work with a Java server at the enterprise level and I need to create token based authentication. The front end uses PHP and communicates with the back end of Java via SOAP.

I was thinking of using Guava HashBiMap to help me solve this problem. This would be useful for me, because I could generate UUID tokens as keys and store User objects as values ​​in a static HashBiMap. When the user first successfully logs in, the User will be added to the HashBiMap, and the response to the input will return the generated UUID token. Subsequent SOAP requests for the same user will be made using only the token.

The problem I'm currently facing is the need for some sort of eviction logic that would allow these tokens to be squeezed out after 30 minutes of inactivity. In my research, it turned out that HashBiMap does not support eviction like Guava MapMaker .

Does anyone have any recommendations on how I can use HashBiMap and support eviction for inaction? If this approach is not perfect, I am open to other strategies.

Update:

I think I need to use HashBiMap because I want to be able to search for the User object on the map and get my existing token if the User is still on the map. For example, if a user closes his browser within a 30-minute window, and after a few minutes returns and logs in again, I need to check if the user exists on the map so that I can return my existing token (since it is still technically valid).

+4
source share
2 answers

The simplest answer: no, you cannot have a HashBiMap with automatic eviction. The maps that MapMaker makes are specialized parallel displays. HashBiMap is basically just a wrapper around two HashMap s.

One option might be to save the UUID to User MapMaker map created by MapMaker with eviction and save the User to UUID mapping in another MapMaker created map with weak keys. When an entry on the card with the eviction is displayed, the entry in the reverse card should be invalid in the near future due to the fact that the cleared UUID link is cleared (if the links to the UUID not contained elsewhere). Even if this mapping still exists when the user logs in again, when you look at the UUID on the evicted card and find no record for him, you know that you need to create a new UUID and create a new mapping.

Of course, you need to consider any potential concurrency problems when doing all this.

+3
source

To answer echo @ColinD, HashBiMap is an awkward map wrapper; as such, you will not automatically see changes from the MapMaker map reflected in BiMap .

All is not lost. @ColinD suggested using two cards. To do this even further, why not wrap these two cards in a custom BiMap implementation, which is based on the view, rather than copying the original map (as HashBiMap does). This will give you the expressive API from BiMap with the required user functionality.

+2
source

All Articles