LoginSignup
0
0

More than 5 years have passed since last update.

あまりものを考えないキャッシュの作り方

Posted at

要件

ライブラリの選定が面倒だったりで、あまりものを考えたくないけどオブジェクトをキャッシュしたいとき。
キャッシュサイズが小さく、JVMが起動している間はキャッシュクリアする必要ない場合。
ただ、並列処理には対応しなければいけない。
このくらいの要件であれば、ライブラリなど要らず簡単に実装できます。

実装方法

ConcurrentHashMap#computeIfAbsent使う

例えば、特定のクラスからpublicなフィールドを取得したい場合、こんな感じ。

public class PublicFieldCache {
  private static final Map<Class<?>, Field[]> cache = new ConcurrentHashMap<>();

  public static Field[] getFields(Class<?> type) {
    return cache.computeIfAbsent(type, Class::getFields);
  }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0