转载自 Java8-本地缓存
这里我将会给大家演示用ConcurrentHashMap类和lambda表达式实现一个本地缓存。因为Map有一个新的方法可以在key为Null的时候自动计算一个新的value值。非常完美的实现cache。来看下代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
public
static
void
main(String[] args) {
for
(
int
i =
0
; i <
10
; i++)
System.out.println(
"f("
+ i +
") = "
+ fibonacci(i));
}
static
int
fibonacci(
int
i) {
if
(i ==
0
)
return
i;
if
(i ==
1
)
return
1
;
System.out.println(
"Calculating f("
+ i +
")"
);
return
fibonacci(i -
2
) + fibonacci(i -
1
);
}
|
当然,这种方式很傻瓜了。即使对于一个非常小的数,例如fibonacci(5),上面的代码打印出很多行,而且都是在进行重复计算,输出如下(只截取一部分):
1
2
3
4
5
6
7
8
9
10
11
12
13
|
Calculating f(
6
)
Calculating f(
4
)
Calculating f(
2
)
Calculating f(
3
)
Calculating f(
2
)
Calculating f(
5
)
Calculating f(
3
)
Calculating f(
2
)
Calculating f(
4
)
Calculating f(
2
)
Calculating f(
3
)
Calculating f(
2
)
f(
6
) =
8
|
我们想要做的就是创建一个缓存,用来计算斐波那契数列。最直接的方法就是在缓存中存放所有的value值。cache的创建如下:
1
|
static
Map<Integer, Integer> cache =
new
ConcurrentHashMap<>();
|
(译者注:这种写法在Java8中是允许的)
声明cache之后,通过Map.computeIfAbsent() 方法,可以在key所对应的value值不存在的情况下,计算一个新的value值。超高速缓存(Caching)!由于这个方法是自动执行的,而且我们使用了 ConcurrentHashMap对象,这个缓存是线程安全的,不需要手动的去写同步方法。另外,它不仅仅可以处理斐波那契额数列,在其他地方也可以被重复使用。
不过现在,我们看看如何在fibonacci()方法中使用缓存。
1
2
3
4
5
6
7
8
9
10
11
|
static
int
fibonacci(
int
i) {
if
(i ==
0
)
return
i;
if
(i ==
1
)
return
1
;
return
cache.computeIfAbsent(i, (key) ->
fibonacci(i -
2
)
+ fibonacci(i -
1
));
}
|
瞧瞧。不能比这个再简单了吧。想要证明吗?好吧,每当我们计算一个新值的时候,都在控制台输出信息:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
static
int
fibonacci(
int
i) {
if
(i ==
0
)
return
i;
if
(i ==
1
)
return
1
;
return
cache.computeIfAbsent(i, (key) -> {
System.out.println(
"Slow calculation of "
+ key);
return
fibonacci(i -
2
) + fibonacci(i -
1
);
});
}
|
程序输出如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
f(
0
) =
0
f(
1
) =
1
Slow calculation of
2
f(
2
) =
1
Slow calculation of
3
f(
3
) =
2
Slow calculation of
4
f(
4
) =
3
Slow calculation of
5
f(
5
) =
5
Slow calculation of
6
f(
6
) =
8
Slow calculation of
7
f(
7
) =
13
Slow calculation of
8
f(
8
) =
21
Slow calculation of
9
f(
9
) =
34
|
在Java7下又如何实现呢?
这样代码就会多一些,我们可以使用double-checked locking来实现:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
static
int
fibonacciJava7(
int
i) {
if
(i ==
0
)
return
i;
if
(i ==
1
)
return
1
;
Integer result = cache.get(i);
if
(result ==
null
) {
synchronized
(cache) {
result = cache.get(i);
if
(result ==
null
) {
System.out.println(
"Slow calculation of "
+ i);
result = fibonacci(i -
2
)
+ fibonacci(i -
1
);
cache.put(i, result);
}
}
}
return
result;
}
|
注:你实际的解决方案很可能会用到Guava Caches。
总结:Lambdas 表达式是Java8中非常重要的一部分。我们不要忘记添加到库中的所有的新特性。
原文链接: Jooq 翻译: ImportNew.com - 踏雁寻花译文链接: http://www.importnew.com/10227.html