Is it possible to remove a key and value from a HashMap if its key is not available for a certain time

I have a requirement when I need to make sure that no user can do multiple logins So for this I made the login system centralized , which after the user successfully logs in, I store it in the Authenticator class , as shown below, and removing it from the HashMap when the user clicks on exit

public final class Authenticator {
    private static Authenticator authenticator = null;
      Map<String, String> usersStorage = new HashMap<String,String>();
     private Authenticator() {}
    public static Authenticator getInstance() {
        if ( authenticator == null ) {
            authenticator = new Authenticator();
        }
        return authenticator;
    }
    public Map<String, String> getusersStorage() {
        return usersStorage;
    }
    }

      

That being said, everything works well.

I have some negative scenarios to handle and this

  • User can close the browser without pressing "Exit" ( Ctrl + W / browser cross button )

In this case, you can remove the key and value from the HashMap if it has been idle for 15 minutes

please share your ideas on approaching this requirement.

+3


source to share


3 answers


Basically you need session management. When the user is logged in, start a session and keep updating the session whenever the user takes any action on your website. And if a user is inactive for a certain amount of time (session time), remove that user from the session store.



If you are not interested in this session management and just want to use a "Map" type of technology, you can switch to any cache engine (eg EhCache). He will do what you asked. But I prefer session management for this particular scenario.

+3


source


Consider Google Guava. Cache classes are very versatile and also support timeout: https://code.google.com/p/guava-libraries/wiki/CachesExplained



0


source


Typically for user centric applications, you will have an application server that takes care of session management if configured correctly, for example. Apache Tomcat will look for an attribute session-timeout

in web.xml

, which will look like this:

<session-config>
    <session-timeout>30</session-timeout>
</session-config>

      

The value is taken in a matter of minutes.

0


source







All Articles