Singleton (or Multiton) Pattern Based on Elapsed Time

249 Views Asked by At

Below I've implemented the Multiton pattern but I think this question applies equally to the Singleton pattern:

private static ConcurrentHashMap<String, LocatorDAO> instances = new   ConcurrentHashMap<String, LocatorDAO>();

public static LocatorDAO getInstance(String page String field) 
{
    String instanceID = page + " " + field; 
    LocatorDAO result = instances.get(instanceID);

    if (result == null) 
    {

        LocatorDAO m = new LocatorDAO(page, field);
        result = instances.putIfAbsent(instanceID, m);

        if (result == null)
            result = m;
    }

    return result;
}

I would like to modify this design by instantiating a new instance every 300 seconds - so if 300 seconds passed from the time we instantiated the previous instance I would like to instantiate it again (or if the instance was never instantiated).

How could this be done?

1

There are 1 best solutions below

0
code On

The solution: Save the timestamp whenever an instance is created. Whenever a new instance is created, check the saved timestamp and find the time difference.

How to implement: There are at least two ways that you can achieve this:

  1. Add the creation timestamp to instanceID and search through all the keys manually. This is a simple solution but will be slower because you'll have to search through all the keys in your hash map.

  2. Implement a bean class that will have two fields LocatorDAO and a long field to save the creation time. During creation, if there is an item in the hash map, check it's creation time and if it is older than 300 seconds, create a new instance

Hope this answer (without code examples) is good enough.