2

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?

Kevin Little
  • 263
  • 1
  • 4
  • 10
  • Note: you could use computeIfAbsent to simplify your current code. See for example: http://stackoverflow.com/a/18149547/829571 – assylias May 01 '17 at 18:31
  • Not really sure how much flexibility you have in your `HashMap`. Is it tightly-coupled with the rest of your code? If so are you forced into using a static local timestamp within `getInstance`? – jiveturkey May 01 '17 at 20:03

1 Answers1

0

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.

code
  • 2,283
  • 2
  • 19
  • 27