Rather than just 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(String var), which you override by coding the logic that builds the cached value based on the doLoad(String var) method’s argument.
To retrieve a value that you’ve cached with CacheBuilder, you don’t call the doLoad(String var) method directly. Instead, it’s called indirectly by Salesforce the first time you reference the class 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(String var) method is called again to build the value and then return it. As a result, you don’t execute put() methods when using the CacheBuilder interface. And because the doLoad(String var) method checks for cache misses, you don’t have to write the code to check for nulls yourself.
Let’s look at an example. Suppose you’re coding an Apex controller class for a Visualforce page. In the Apex class, you often run a SOQL query that looks 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.
In your controller class, create an inner class that implements the CacheBuilder interface and overrides the doLoad(String var) method. Then add the SOQL code to the doLoad(String 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; } }
To retrieve the User record from the org cache, execute the Org.get(cacheBuilder, key) method, passing it the UserInfoCache class and the user ID. Similarly, use Session.get(cacheBuilder, key) and Partition.get(cacheBuilder, key) to retrieve the value from the session or partition cache, respectively.
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. If Salesforce finds a cached value, it returns it. For this example, the cached value is a User record associated with the ID 00541000000ek4c. If Salesforce doesn’t find a value, it executes the doLoad(String var) method of UserInfoCache again (and reruns the SOQL query), caches the User record, and then returns it.
Follow these requirements when you code a class that implements the CacheBuilder interface.