Java Reference
In-Depth Information
BigObject obj = null;
// Check if we have a cache for this id
if (cache[id] == null) {
// We have not cached the object yet. Cache and return it.
obj = createCacheForId(id);
return obj;
}
// Get the BigObject reference using a soft reference
obj = cache[id].get();
// Make sure the object has not yet been reclaimed
if (obj == null) {
// Garbage collector has reclaimed the object.
// Cache it again and return the newly cached object.
obj = createCacheForId(id);
}
return obj;
}
// Creates cache for a given id
private static BigObject createCacheForId(int id) {
BigObject obj = null;
if (id >=0 && id < cache.length) {
obj = new BigObject(id);
cache[id] = new SoftReference<BigObject>(obj);
}
return obj;
}
}
It can cache up to 10 objects of the
BigObject
class with ids from 0 to 9. To get the cached object for a given
id
,
you need to call the
getObjectById()
method. If that
id
has not yet been cached or it was reclaimed by the garbage
collector, the method caches the object. This example is very restrictive and its purpose is only to demonstrate the use
of the
SoftReference
class to maintain a memory-sensitive cache. You can cache only objects with
id
s from 0 to 9.
It can be modified to meet specific requirements. For example, you can use an
ArrayList
to cache the objects instead
of using an array. You can use the
BigObjectCache
class as shown:
// Get the object from cache
BigObject cachedObject = BigObjectCache.getObjectById(5);
/* Do some processing...*/
// You must set the cachedObject to null after you are done with it, so the cached object
// becomes softly reachable and may be reclaimed by the garbage collector.
cachedObject = null;