I have an issue that I've been banging my head at for a while. I've been tasked with a building a Java cache toolkit with various implementations all belonging to a single cache interface. One of the implementations is an actual HashMap. The relevant parts of the code are:
The issue I'm having is that when a user gets an object from the hashamp cache and assigns it a local variable and then changes something in that object via a setter, the actual cache is being affected.
I would like to return a cloned value of the value derived from get(key) but since the interface is purely object I cannot clone it. Any ideas?
Thanks,
The Dan
Code:
private HashMap cache = new HashMap();
public Object get (Object key) throws CacheException
{
try
{
return cache.get(key)
}
catch (Exception e)
{
throw new CacheException("Failed to get key:" + key + " from cache", e);
}
}
public void put (Object key, Object value) throws CacheException
{
synchronized(this.cache) {
try
{
this.cache.put(key, value);
logger.info("putting key:" + key + " value: " + value + " into cache");
}
catch (Exception e)
{
throw new CacheException("Failed to put key:" + key + " and value:" + value + " into cache", e);
}
}
}
The issue I'm having is that when a user gets an object from the hashamp cache and assigns it a local variable and then changes something in that object via a setter, the actual cache is being affected.
I would like to return a cloned value of the value derived from get(key) but since the interface is purely object I cannot clone it. Any ideas?
Thanks,
The Dan