为大计算量的程序添加缓存 作为一个大计算量程序的例子,我们考虑PiBinaryDigitsCalculator这个例子-计算二进制数据pi.仅有的public方法calculateBinaryDigit带有一个参数:整数n,代表需要精确到的位数.例如,1000000,将会返回小数点后的一百万位,通过byte值返回-每位为0或者1.(算法可以参考: http://www.cecm.sfu.ca/~pborwein/PAPERS/P123.pdf) public class PiBinaryDigitsCalculator { /** * Returns the coefficient of 2^n in the binary * eXPansion of pi. * @param n the binary digit of pi to calculate. * @throws ValidityCheckFailedException if the validity * check fails, this means the implementation is buggy * or n is too large for sufficient PRecision to be * retained. */ public byte calculateBinaryDigit(final int n) { return runBBPAlgorithm(n); }
private byte runBBPAlgorithm(final int n) { // Lengthy routine goes here ... }
public synchronized byte calculateBinaryDigit( final int n) {
final Integer N = new Integer(n); Byte B = (Byte) cache.get(N); if (B == null) { byte b = runBBPAlgorithm(n); cache.put(N, new Byte(b)); return b; } else { return B.bytevalue(); } }
private byte runBBPAlgorithm(final int n) { // Lengthy routine goes here ... } }