How to create a cache of key-value pairs in Java?

Use the following code to create a cache of key-value pairs in Java.

import java.util.HashMap;
import java.util.Map;

/**
 * This class is used to create a cache of key value pairs which expires after a given time period. Once a key-value
 * pair is set using the setValue() method, they expire after 5 seconds(default).
 */

public class TimerCache
{
        private Map<String, String>     cacheMap = new HashMap<String, String>();

        public TimerCache()
        {
        }

        public void setValue(final String name, String value)
        {
                cacheMap.put(name, value);
                Thread t = new Thread() {
                        public void run()
                        {
                                try
                                {
                                        Thread.sleep(5 * 1000 * 12 * 5);

                                }
                                catch (InterruptedException e)
                                {

                                        e.printStackTrace();
                                }
                                cacheMap.remove(name);
                        }
                };
                t.start();
        }

        public String getValue(String name)
        {
                return cacheMap.get(name);
        }

        /**
         * @param args
         */

        public static void main(String[] args)
        {
                TimerCache tc = new TimerCache();

                tc.setValue("java", "gosling");
                tc.setValue("c", "ritche");

                try
                {
                        Thread.currentThread().sleep(500);
                }
                catch (InterruptedException e)
                {
                        e.printStackTrace();
                }

                System.out.println(tc.getValue("sibi"));
                System.out.println(tc.getValue("vibu"));
        }
}

Search