Safely Cache Values with the New Cache Builder Interface

The Cache.CacheBuilder interface makes it easy to safely store and retrieve values to a session or org cache. A Platform Cache best practice is to ensure that your code handles cache misses by testing cache requests that return null. You can write this code yourself, or you can use the new Cache.CacheBuilder interface.

Rather than declaring what you want to cache in your Apex class, create an inner class that implements the CacheBuilder interface. The interface has a single method, doLoad(var). When you override doLoad(var), you code the logic that builds the cached value based on its argument. But you don’t call this method directly. Instead, Salesforce calls it indirectly the first time you reference the class that you created that implements CacheBuilder. Subsequent calls get the value from the cache as long as the value exists. If the value doesn’t exist, the doLoad(var) method is called again to build the value.

Let’s look at an example. Suppose you have an Apex class in which you often run a SOQL query to look up a User record based on a user ID. SOQL queries can be expensive, and Salesforce user records don’t typically change much, so the User information is a good candidate for CacheBuilder. The UserInfoCache class implements CacheBuilder and puts the SOQL query inside the doLoad(var) method with the user ID as its parameter.

class UserInfoCache implements Cache.CacheBuilder { 
    public Object doLoad(String userid) { 
        User u = (User)[SELECT Id, IsActive, username FROM User WHERE id =: userid]; 
        return u; 
    } 
} 

This example shows how to get the User record from the org cache.

User batman = (User) Cache.Org.get(UserInfoCache.class, ‘00541000000ek4c');

When you run the get() method, Salesforce searches the cache using a unique key that consists of the strings 00541000000ek4c and UserInfoCache (the class that implements CacheBuilder). If Salesforce finds a cached value, it returns it. Following our example, the cached value is a User record associated with the ID 00541000000ek4c. If Salesforce doesn’t find a value, it executes the doLoad(var) method of UserInfoCache again (and reruns the SOQL query), caches the User record, and then returns it.

For more information and examples, see the Platform Cache feature documentation and Cache namespace reference documentation in the Apex Developer Guide