如何使用Guava缓存而不是HashMap?

时间:2015-10-09 07:26:17

标签: java caching guava

我使用HashMap来存储斐波那契值。

以下是此代码执行的输出:

Enter n: 500000
F(500000) = 2955561408 ... computed in 5,141 ms
Enter n: 500000
F(500000) = 2955561408 ... computed in 0 ms

它缓存很好,并且返回结果很好

我想用更好的Guava cache替换它,我已经失去了任何利润。 代码执行输出:

Enter n: 500000
F(500000) = 2955561408 ... computed in 5,184 ms
Enter n: 500000
F(500000) = 2955561408 ... computed in 5,086 ms

以下是程序代码:

public class CachedFibonacci {
    private static Map<BigDecimal, BigDecimal> previousValuesHolder;
    static {
        previousValuesHolder = new HashMap<>();
        previousValuesHolder.put(BigDecimal.ZERO, BigDecimal.ZERO);
        previousValuesHolder.put(BigDecimal.ONE, BigDecimal.ONE);
    }

    private static LoadingCache<BigDecimal, BigDecimal> cachedFibonacci = CacheBuilder.newBuilder()
            .expireAfterWrite(3, TimeUnit.MINUTES)
            .maximumSize(500000)
            .concurrencyLevel(5)
            .weakKeys()
            .build(new CacheLoader<BigDecimal, BigDecimal>() {
                @Override
                public BigDecimal load(BigDecimal key) throws Exception {
                    return getFibonacciByKey(key);
                }
            });

    private static BigDecimal getFibonacciByKey(BigDecimal key) {
        long number = key.longValue();

        BigDecimal olderValue = BigDecimal.ONE,
                oldValue = BigDecimal.ONE,
                newValue = BigDecimal.ONE;

        for (int i = 3; i <= number; i++) {
            newValue = oldValue.add(olderValue);
            olderValue = oldValue;
            oldValue = newValue;
        }
        return newValue;
    }

    public static BigDecimal getGuavaCache(long number) {
        if (0 == number) {
            return BigDecimal.ZERO;
        } else if (1 == number) {
            return BigDecimal.ONE;
        } else {
            return cachedFibonacci.getUnchecked(BigDecimal.valueOf(number));
        }
    }

    public static BigDecimal getCachedFibonacciOf(long number) {
        if (0 == number) {
            return BigDecimal.ZERO;
        } else if (1 == number) {
            return BigDecimal.ONE;
        } else {
            if (previousValuesHolder.containsKey(BigDecimal.valueOf(number))) {
                return previousValuesHolder.get(BigDecimal.valueOf(number));
            } else {
                BigDecimal olderValue = BigDecimal.ONE,
                        oldValue = BigDecimal.ONE,
                        newValue = BigDecimal.ONE;

                for (int i = 3; i <= number; i++) {
                    newValue = oldValue.add(olderValue);
                    olderValue = oldValue;
                    oldValue = newValue;
                }
                previousValuesHolder.put(BigDecimal.valueOf(number), newValue);
                return newValue;
            }
        }
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.print("Enter n: ");
            long inputNumber = scanner.nextLong();
            if (inputNumber >= 0) {
                long beginTime = System.nanoTime();
//                BigDecimal fibo = getCachedFibonacciOf(inputNumber);
                BigDecimal fibo = getGuavaCache(inputNumber);

                long endTime = System.nanoTime();
                long delta = endTime - beginTime;

                System.out.printf("F(%d) = %.10s ... computed in %,d ms\n", inputNumber, fibo, delta / 1_000_000);
            } else {
                System.err.println("You must enter number > 0");
                System.out.println("try, enter number again, please:");
                break;
            }
        }
    }
}

正如我想当你调用cachedFibonacci.getUnchecked()时,如果它被缓存,它应该返回缓存的值,否则计算它并缓存。

为什么此代码会使用Guava缓存再次计算?
如何解决这个问题?

1 个答案:

答案 0 :(得分:5)

如果删除行

.weakKeys()

来自构建缓存,而不是你会看到加速计算。

来自javaDoc

  
      
  • 警告:使用此方法时,生成的缓存将使用标识({@code ==})

  •   
  • 比较以确定键的相等性。
  •