何がやりたいか?

例題

キャッシング Aspect

あんまり遅いので、Fibonacci#fibonacci(n) の結果をキャッシングする Aspect を適用する。

package com.snail.exam.aj.fibonacci;

import java.util.LinkedHashMap;
import java.util.Map;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;

@Aspect
public class FibonacciCache {
  
  private static final int MAX_ENTRIES = 2;
  private static Map<Integer,Long> cache = new LinkedHashMap<Integer,Long>(){
    @Override
    protected boolean removeEldestEntry(Map.Entry<Integer,Long> eldest) {
      return size() > MAX_ENTRIES;
           }
  };
  
  public static int getCacheSize(){
    return cache.size();
  }
  
  @Around("call(long com.snail.exam.aj.fibonacci.Fibonacci.fibonacci(int))")
  public long cacheFibonacci(ProceedingJoinPoint thisJoinPoint) throws Throwable{
    
    Object[] args = thisJoinPoint.getArgs();
    Integer arg = (Integer)args[0];
    
    if(!cache.containsKey(arg)){
      cache.put(arg, (Long)thisJoinPoint.proceed(thisJoinPoint.getArgs()));
    }
    
    return cache.get(arg);
  }
}

実行結果

ajCache3.png

なんでそうなるのか?


Java#AspectJ


*1 さっき、元プログラムに手を入れなくても高速化できると言いましたが(^^;

添付ファイル: fileajCache2.png 1956件 [詳細] fileajCache1.png 2006件 [詳細] fileajCache3.png 1997件 [詳細]

トップ   編集 凍結 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 単語検索 最終更新   ヘルプ   最終更新のRSS   sitemap
Last-modified: 2008-04-12 (土) 01:37:39 (5858d)
Short-URL: https://at-sushi.com:443/pukiwiki/index.php?cmd=s&k=b80df26048
ISBN10
ISBN13
9784061426061