Java 8-local cache

Source: Internet
Author: User

Here I will show you how to use the ConcurrentHashMap class and lambda expression to implement a local cache. Because Map has a new method that automatically calculates a new value when the key is Null. Perfect cache implementation. Let's look at the Code:

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);}

Of course, this method is a dumb. Even for a very small number, such as fibonacci (5), the above Code prints a lot of rows and is repeatedly computed. The output is as follows (only part of the output ):

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

What we want to do is to create a cache to calculate the Fibonacci series. The most direct method is to store all value values in the cache. The cache is created as follows:

static Map
  
    cache = new ConcurrentHashMap<>();
  

(Note: This method is allowed in Java 8)

After the cache is declared, a new value can be calculated if the value corresponding to the key does not exist using the Map. computeIfAbsent () method. Caching )! Because this method is automatically executed and we use the ConcurrentHashMap object, this cache is thread-safe and does not need to be manually written to the synchronization method. In addition, it can not only process the Fibonacci number series, but also be reused elsewhere.

But now let's look at how to use caching In the fibonacci () method.

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));}

Look. It's no longer easier than that. Do you want to prove it? Well, whenever we calculate a new value, the information is output on the console:

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);    });}

The program output is as follows:

f(0) = 0f(1) = 1Slow calculation of 2f(2) = 1Slow calculation of 3f(3) = 2Slow calculation of 4f(4) = 3Slow calculation of 5f(5) = 5Slow calculation of 6f(6) = 8Slow calculation of 7f(7) = 13Slow calculation of 8f(8) = 21Slow calculation of 9f(9) = 34
How can we implement it in Java 7?

In this way, there will be more code. We can use double-checked locking to implement:

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;}

Note: your actual solution is likely to use Guava Caches.

Conclusion: Lambdas expressions are an important part of Java 8. Do not forget all the new features added to the library.

Original article: http://blog.jooq.org/2014/02/28/java-8-friday-goodies-easy-as-pie-local-caching/

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.