Map<E, SoftReference<T>> cache = new ConcurrentHashMap<E, SoftReference<T>>();
I have map declared a map like the above one which I'm using as a Cache.
The problem is I'm to perform all operations on the Cache immediately after adding an item to the Cache but not later.
For ex:
cache.add("Username", "Tom");
if(cache.contains("Username")) returns true but
String userName = (String)cache.get("Username") returns null.
This happens only after a long time.
If I get the value after a few hours of adding it to the cache, I get the value correctly. If I get the value after a long time, say more than 15-20 hrs, I get null.
When GC clears SoftReference objects, will the key remain in HashMap? Is that the reason for this behaviour?
Yes, that is normal behaviour.
The SoftReference is garbage collected, resulting in the value in the Map being set to null.
It is the same as setting the value of a certain key to null for other types of maps (eg. Map)