Sunday, August 17, 2014

Writing generic class

In one of my former posts "Incorrect usage of WeakHashMap" I have shown code for the class WeakCache. The class works all right, but since release Java 1.5 that kind of classes should be written as generic. So let write generic WeakCache.

That is old version of WeakCache

public class WeakCache {

 WeakHashMap<Object, Object> conditions = new WeakHashMap<Object, Object>();

 public synchronized Object get(Object condition) {
  if (condition == null)
   throw new NullPointerException("condition");
  Object cachedCondition = conditions.get(condition);
  if (cachedCondition == null) {
   cachedCondition = condition;
   conditions.put(cachedCondition, new WeakReference<Object>(
     cachedCondition));
  } else {
   @SuppressWarnings("unchecked")
   WeakReference<Object> weakReference = (WeakReference<Object>) cachedCondition;
   cachedCondition = weakReference.get();
  }
  return cachedCondition;
 }

}

And here the new one:
public class WeakCache<K extends TargetCondition> {

 private WeakHashMap<K, WeakReference<K>> conditions = new WeakHashMap<K, WeakReference<K>>();

 public synchronized K get(K condition) {
  if (condition == null)
   throw new NullPointerException("condition");
  K cachedCondition;
  WeakReference<K> weakReference = conditions.get(condition);
  if (weakReference == null) {
   cachedCondition = condition;
   conditions.put(cachedCondition, new WeakReference<K>(cachedCondition));
  } else {
   cachedCondition = weakReference.get();
  }
  return cachedCondition;
 }


}


No comments:

Post a Comment