Cache in Java

Overview

Caches are small, fast memory locations that store copies of frequently accessed data to speed up data retrieval. They play a crucial role in enhancing the performance of applications by reducing the time needed to access data from slower main memory. However, when data is not found in the cache, a cache miss occurs, necessitating access to the slower main memory, which can significantly impact performance. Understanding cache behavior is essential in Java performance tuning to minimize cache misses and optimize application efficiency.

Understanding Cache Misses

To illustrate the concept of cache misses, consider the following Java code example:

[Listing 7.1 Understanding Cache Misses](https://livebook.manning.com/book/the-well-grounded-java-developer-second-edition/chapter-7/217)

public class Caching {
    private final int ARR_SIZE = 2 * 1024 * 1024;
    private final int[] testData = new int[ARR_SIZE];
 
    private void touchEveryItem() {
        for (int i = 0; i < testData.length; i = i + 1) {
            testData[i] = testData[i] + 1;                    #1
        }
    }
 
    private void touchEveryLine() {
        for (int i = 0; i < testData.length; i = i + 16) {
            testData[i] = testData[i] + 1;                    #2
        }
    }
 
    private void run() {
        for (int i = 0; i < 10_000; i = i + 1) {              #3
            touchEveryLine();
            touchEveryItem();
        }
        System.out.println("Line     Item");
        for (int i = 0; i < 100; i = i + 1) {
            long t0 = System.nanoTime();
            touchEveryLine();
            long t1 = System.nanoTime();
            touchEveryItem();
            long t2 = System.nanoTime();
            long el1 = t1 - t0;
            long el2 = t2 - t1;
            System.out.println("Line: "+ el1 +" ns ; Item: "+ el2);
        }
    }
 
    public static void main(String[] args) {
        Caching c = new Caching();
        c.run();
    }
}
#1 Touches every item
#2 Touches each cache line
#3 Warms up the code

In this example, the touchEveryItem method iterates over every element in the array, potentially causing more cache misses as each element is accessed individually. In contrast, the touchEveryLine method accesses elements in steps of 16, which corresponds to the typical size of a cache line, thereby reducing the number of cache misses by taking advantage of spatial locality.

Testing Cache Behavior

Testing cache behavior can be done using specification-style testing frameworks like Spek in Kotlin. This approach allows for a structured and readable way to define and execute tests, particularly useful for testing cache-related functionalities.

Example: Testing an In-Memory Cache

The following Kotlin code demonstrates how to test an in-memory cache using Spek:

import org.spekframework.spek2.Spek
import org.junit.jupiter.api.Assertions.assertEquals
import java.math.BigDecimal

object InMemoryCachedPriceSpek : Spek({
    group("empty cache") {
        test("gets default value") {
            val stubbedPrice = StubPrice()
            val cachedPrice = InMemoryCachedPrice(stubbedPrice)

            assertEquals(BigDecimal(10), cachedPrice.initialPrice)
        }

        test("gets same value when called again") {
            val stubbedPrice = StubPrice()
            val cachedPrice = InMemoryCachedPrice(stubbedPrice)

            val first = cachedPrice.initialPrice
            val second = cachedPrice.initialPrice
            assertTrue(first === second)               #1
        }
    }
})
#1 === is Kotlin’s operator for reference equality, so this checks that we get the exact same object between calls, not just an identical value.

In this example, the InMemoryCachedPriceSpek object defines a group of tests for an empty cache scenario. The tests verify that the cache returns a default value and that repeated calls return the same object, ensuring that the cache is functioning correctly.

By using specification-style testing, developers can create clear and maintainable tests that verify the behavior of cache implementations, ensuring that they perform as expected under various conditions.