キャッシュの作り方。

キャッシュの機能を扱いたいときにはjava.refパッケージのクラスを使うのですが、
SoftReference, WeakReference, PhantomReference の3種類のクラスがあります(私は違いがよく分かっていません)。
以下は SoftReference を使って実装したときの例です。

巨大データが1つのとき。

      private SoftReference ref = null;
      public BigData getBigData() {
            BigData data = null;
            if (ref != null) data = (BigData) ref.get();
            if (data == null) {
                  data = ...;       // でかいデータを取得or作成
                  ref = new SoftReference(data);
            }
            return data;
      }

巨大なデータを(キー+値)の形で複数持ちたいとき。

      private HashMap map = new HashMap();
      public BigData getBigData(Object key) {
            SoftReference ref = (SoftReference) map.get(key);
            if (ref == null || ref.get() == null) {
                  BigData data = ...;           // でかいデータを取得or作成
                  map.put(key, new SoftReference(data));
                  return data;
            }
            return (BigData) ref.get();
      }