Newer Version Available

This content describes an older version of this product. View Latest

Org Class

Use the Cache.Org class to add, retrieve, and manage values in the org cache. Unlike the session cache, the org cache is not tied to any session and is available to the organization across requests and to all users.

Namespace

Cache

Usage

Cache Key Format

This table lists the format of the key parameter that some methods in this class take, such as put, get, and contains.

Key Format Description
namespace.partition.key Fully qualified key name.
key Refers to a partition marked as default when the namespace.partition prefix is omitted.
local.partition.key Use the local prefix to refer to the org’s namespace when the org doesn’t have a namespace defined. If the org has a namespace defined, the local prefix also refers to that org’s namespace.
  • If no default partition is specified in the org, calling a cache method without fully qualifying the key name causes a Cache.Org.OrgCacheException to be thrown.
  • The local prefix in an installed managed package refers to the namespace of the subscriber org and not the package’s namespace. The cache put calls aren’t allowed in a partition that the invoking class doesn’t own.

Note

Example

This class is the controller for a sample Visualforce page (shown in the subsequent code sample). The cached values are initially added to the cache by the init() method, which the Visualforce page invokes when it loads through the action attribute. The cache keys don’t contain the namespace.partition prefix. They all refer to the default partition in your org. To run this sample, create a partition and mark it as default.

The Visualforce page contains four output components. These components call get methods on the controller that returns the following values from the cache: a date, data based on the MyData inner class, a counter, a text value, and a list. The size of the list is also returned.

The Visualforce page also contains two buttons. The Rerender button invokes the go() method on the controller. This method increases the values of the counter and the custom data in the cache. When you click Rerender, the two counters increase by one each time. The go() method retrieves the values of these counters from the cache, increments their values by one, and stores them again in the cache.

The Remove datetime Key button deletes the date-time value (with key datetime) from the cache. As a result, the value next to Cached datetime: is cleared on the page.

If another user logs in and runs this sample, this user gets the cache values that were last added or updated by the previous user. For example, if the counter value was five, the next user sees the counter value as increased to six.

Note

1public class OrgCacheController {
2
3    // Inner class.
4    // Used as the data type of a cache value.
5    class MyData {    
6        public String value { get; set; }
7        public Integer counter { get; set; }
8        
9        public MyData(String value) {
10            this.value = value;
11            this.counter = 0;
12        }
13        
14        public void inc() {
15            counter++;
16        }
17        
18        override public String toString() {
19            return this.value + ':' + this.counter;
20        }    
21    }
22    
23    // Apex List.
24    // Used as the data type of a cached value.
25    private List<String> numbers = 
26            new List<String> { 'ONE', 'TWO', 'THREE', 'FOUR', 'FIVE' }; 
27               
28    // Constructor of the controller for the Visualforce page. 
29    public OrgCacheController() {  
30    }
31            
32    // Adds various values to the cache.
33    // This method is called when the Visualforce page loads.
34    public void init() {  
35        // All key values are not qualified by the namespace.partition
36        // prefix because they use the default partition.
37        
38        // Add counter to the cache with initial value of 0
39        //  or increment it if it's already there.
40        if (!Cache.Org.contains('counter')) {
41            Cache.Org.put('counter', 0);
42        } else {
43            Cache.Org.put('counter', getCounter() + 1);
44        }
45              
46        // Add the datetime value to the cache only if it's not already there.
47        if (!Cache.Org.contains('datetime')) {
48            DateTime dt = DateTime.now();
49            Cache.Org.put('datetime', dt);
50        }
51     
52        // Add the custom data to the cache only if it's not already there.
53        if (!Cache.Org.contains('data')) {
54            Cache.Org.put('data', new MyData('Some custom value'));
55        }
56                
57        // Add a list of number to the cache if not already there.
58        if (!Cache.Org.contains('list')) {  
59            Cache.Org.put('list', numbers);
60        }
61                
62        // Add a string value to the cache if not already there.
63        if (!Cache.Org.contains('output')) {
64            Cache.Org.put('output', 'Cached text value');
65        }
66    }
67    
68    // Return counter from the cache.
69    public Integer getCounter() {
70        return (Integer)Cache.Org.get('counter');
71    }
72    
73    // Return datetime value from the cache.
74    public String getCachedDatetime() {
75        DateTime dt = (DateTime)Cache.Org.get('datetime');
76        return dt != null ? dt.format() : null;
77    }
78    
79    // Return cached value whose type is the inner class MyData.
80    public String getCachedData() {
81        MyData mydata = (MyData)Cache.Org.get('data');
82        return mydata != null ? mydata.toString() : null;
83    }
84    
85    // Return output from the cache.
86    public String getOutput() {
87        return (String)Cache.Org.get('output');
88    }
89    
90    // Return list from the cache.
91    public List<String> getList() {
92        return (List<String>)Cache.Org.get('list');
93    }
94    
95    // Method invoked by the Rerender button on the Visualforce page.
96    // Updates the values of various cached values.
97    // Increases the values of counter and the MyData counter if those 
98    //   cache values are still in the cache.
99    public PageReference go() {
100        // Increase the cached counter value or set it to 0 
101        //  if it's not cached.        
102        if (Cache.Org.contains('counter')) {
103            Cache.Org.put('counter', getCounter() + 1);
104        } else {
105            Cache.Org.put('counter', 0);
106        }        
107    
108        // Get the custom data value from the cache.
109        MyData d = (MyData)Cache.Org.get('data');
110        // Only if the data is already in the cache, update it.
111        if (Cache.Org.contains('data')) {
112            d.inc();
113            Cache.Org.put('data', d);            
114        }        
115
116        return null;
117    }
118    
119    // Method invoked by the Remove button on the Visualforce page.
120    // Removes the datetime cached value from the org cache.
121    public PageReference remove() {
122        Cache.Org.remove('datetime');
123
124        return null;
125    }
126}

This is the Visualforce page that corresponds to the OrgCacheController class.

1<apex:page controller="OrgCacheController" action="{!init}">
2
3    <apex:outputPanel id="output">
4        <br/>Cached datetime: <apex:outputText value="{!cachedDatetime}"/>
5        <br/>Cached data: <apex:outputText value="{!cachedData}"/>
6        <br/>Cached counter: <apex:outputText value="{!counter}"/>
7        <br/>Output: <apex:outputText value="{!output}"/>
8        <br/>Repeat: <apex:repeat var="item" value="{!list}">
9            <apex:outputText value="{!item}"/>&nbsp;
10        </apex:repeat>
11        <br/>List size: <apex:outputText value="{!list.size}"/>
12    </apex:outputPanel>
13    
14    <br/><br/>
15    <apex:form >
16        <apex:commandButton id="go" action="{!go}" value="Rerender" rerender="output"/>
17        <apex:commandButton id="remove" action="{!remove}" value="Remove datetime Key" rerender="output"/>
18    </apex:form>
19
20</apex:page>

This is the output of the page after clicking the Rerender button twice. The counter value could differ in your case if a key named counter was already in the cache before running this sample.

1Cached datetime:8/11/2015 1:58 PM
2Cached data:Some custom value:2
3Cached counter:2
4Output:Cached text value
5Repeat:ONE TWO THREE FOUR FIVE 
6List size:5

Org Constants

The Org class provides a constant that you can use when setting the time-to-live (TTL) value.
Constant Description
MAX_TTL_SECS Represents the maximum amount of time, in seconds, to keep the cached value in the org cache.

Org Methods

The following are methods for Org. All methods are static.

contains(key)

Returns true if the org cache contains a cached value corresponding to the specified key.

Signature

public static Boolean contains(String key)

Parameters

key
Type: String
A case-sensitive string value that uniquely identifies a cached value. For information about the format of the key name, see Usage.

Return Value

Type: Boolean

true if a cache entry is found. Othewise, false.

contains(keys)

Returns true if the org cache contains values for the specified key entries.

Signature

public static List<Boolean> contains(List<String> keys)

Parameters

keys
Type: List<String>
A list of keys that identifies cached values. For information about the format of the key name, see Usage.

Return Value

Type: List<Boolean>

true if the key entries are found. Othewise, false.

contains(setOfKeys)

Returns true if the org cache contains values for a specified set of keys.

Signature

public static Map <String, Boolean> contains (Set<String> keys)

Parameters

setOfKeys
Type: Set <String>

A set of keys that uniquely identifies cached values. For information about the format of the key name, see Usage

Return Value

Type: Map <String, Boolean>

Returns the cache key and corresponding Boolean value indicating that the key entry exists. The Boolean value is false if the key entry doesn't exist.

Usage

The number of input keys cannot exceed the maximum limit of 10.

Example

In this example, the code checks for the presence of multiple keys on the default partition. It fetches the cache key and the corresponding Boolean value for the key entry from the org cache of the default partition.

1Set<String> keys = new Set<String>{'key1','key2','key3','key4','key5'};
2Map<String,Boolean> result = Cache.Org.contains(keys);
3for(String key : result.keySet()) {
4    system.debug('key: ' + key);
5    system.debug('Is Key Present in the cache : ' +  result.get(key));
6}

In this example, the code checks for the presence of multiple keys on different partitions. It fetches the cache key and the corresponding Boolean value for the key entry from the org cache of different partitions.

1// Assuming there are three partitions p1, p2, p3 with default 'local' namespace
2
3Set<String> keys = new Set<String>{'local.p1.key','local.p2.key', 'local.p3.key'};
4Map<String,Boolean> result = Cache.Org.contains(keys);
5for(String key : result.keySet()) {
6    system.debug('key: ' + key);
7    system.debug('Is Key Present in the cache : +  result.get(key));
8}

get(key)

Returns the cached value corresponding to the specified key from the org cache.

Signature

public static Object get(String key)

Parameters

key
Type: String
A case-sensitive string value that uniquely identifies a cached value. For information about the format of the key name, see Usage.

Return Value

Type: Object

The cached value as a generic object type. Cast the returned value to the appropriate type.

Usage

Because Cache.Org.get() returns an object, cast the returned value to a specific type to facilitate use of the returned value.

1// Get a cached value
2Object obj = Cache.Org.get('ns1.partition1.orderDate');
3// Cast return value to a specific data type
4DateTime dt2 = (DateTime)obj;

If a Cache.Org.get() call doesn’t find the referenced key, it returns null.

get(cacheBuilder, key)

Returns the cached value corresponding to the specified key from the org cache. Use this method if your cached value is a class that implements the CacheBuilder interface.

Signature

public static Object get(System.Type cacheBuilder, String key)

Parameters

cacheBuilder
Type: System.Type
The Apex class that implements the CacheBuilder interface.
key
Type: String
A case-sensitive string value that, combined with the class name corresponding to the cacheBuilder parameter, uniquely identifies a cached value.

Return Value

Type: Object

The cached value as a generic object type. Cast the returned value to the appropriate type.

Usage

Because Cache.Org.get(cacheBuilder, key) returns an object, cast the returned value to a specific type to facilitate use of the returned value.

1return ((DateTime)Cache.Org.get(DateCache.class, 'datetime')).format();

get(keys)

Returns the cached values corresponding to the specified set of keys from the org cache.

Signature

public static Map <String, Object> get (Set <String> keys)

Parameters

keys
Type: Set <String>

A set of keys that uniquely identify cached values. For information about the format of the key name, see Usage.

Return Value

Type: Map <String, Object>

Returns the cache key and corresponding value. Returns null when no corresponding value is found for an input key.

Usage

The number of input keys cannot exceed the maximum limit of 10.

Examples

Fetch multiple keys from the org cache of the default partition.

1Set<String> keys = new Set<String>{'key1','key2','key3','key4','key5'};
2Map<String,Object> result = Cache.Org.get(keys);
3for(String key : result.keySet()) {
4    system.debug('key: ' + key);
5    system.debug('value: ' +  result.get(key));
6}

Fetch multiple keys from the org cache of different partitions.

1// Assuming there are three partitions p1, p2, p3 with default 'local' namespace
2
3Set<String> keys = new Set<String>{'local.p1.key','local.p2.key', 'local.p3.key'};
4Map<String,Object> result = Cache.Org.get(keys);
5for(String key : result.keySet()) {
6    system.debug('key: ' + key);
7    system.debug('value: ' +  result.get(key));
8}

getAvgGetSize()

Returns the average item size of all the keys fetched from the org cache, in bytes.

Signature

public static Long getAvgGetSize()

Return Value

Type: Long

Example

In this example the following keys and their corresponding value sizes are inserted. The code then fetches the keys: key 1, key 2, key 3 and key 4 and returns the average item size of the fetched keys.

Key Key Value Size
key 1 42
key 2 42
key 3 58
key 4 36
key 5 36
1// Inserting keys key1, key2, key3, key4, key5
2Cache.Org.put('key1', 'value1');
3Cache.Org.put('key2', 'value2');
4Cache.Org.put('key3', 'this is a big value !!!');
5Cache.Org.put('key4', 4);
6Cache.Org.put('key5', 5);
7
8
9// Fetching keys - key1, key2, key3, key4
10Object v1 = Cache.Org.get('key1');
11Object v2 = Cache.Org.get('key2');
12Object v3 = Cache.Org.get('key3');
13Object v4 = Cache.Org.get('key4');
14
15// Fetching average get size
16Long val = Cache.Org.getAvgGetSize();
17// Avg item size returned is 44 ( average of 42(key1), 42(key2), 58(key3) and 36(key4) keys that were fetched )
18System.debug('Avg Get Size :' + val);

getAvgGetTime()

Returns the average time taken to get a key from the org cache, in nanoseconds.

Signature

public static Long getAvgGetTime()

Return Value

Type: Long

getAvgValueSize()

Deprecated and available only in API versions 49.0 and earlier. Returns the average item size for keys in the org cache, in bytes.

Signature

public static Long getAvgValueSize()

Return Value

Type: Long

getCapacity()

Returns the percentage of org cache capacity that has been used.

Signature

public static Double getCapacity()

Return Value

Type: Double

Used cache as a percentage number.

getKeys()

Returns a set of all keys that are stored in the org cache and visible to the invoking namespace.

Signature

public static Set<String> getKeys()

Return Value

Type: Set<String>

A set containing all cache keys.

getMaxGetSize()

Returns the maximum item size of all the keys fetched from the org cache, in bytes.

Signature

public static Long getMaxGetSize()

Return Value

Type: Long

Example

In this example the following keys and their corresponding value sizes are inserted. The code fetches the keys: key 1, key 2 and key 4 and returns the maximum key value size from the fetched keys.

Key Key Value Size
key 1 42
key 2 42
key 3 58
key 4 36
key 5 36
1// Inserting keys key1, key2, key3, key4, key5
2Cache.Org.put('key1', 'value1');
3Cache.Org.put('key2', 'value2');
4Cache.Org.put('key3', 'this is a big value !!!');
5Cache.Org.put('key4', 4);
6Cache.Org.put('key5', 5);
7
8
9// Fetching keys - key1, key2, key4
10Object v1 = Cache.Org.get('key1');
11Object v2 = Cache.Org.get('key2');
12Object v4 = Cache.Org.get('key4');
13
14// Fetching max get size
15Long val = Cache.Org.getMaxGetSize();
16// Max item size returned is 42 ( max of 42(key1), 42(key2), and 36(key4) keys that were fetched )
17System.debug('Max Get Size :' + val);

getMaxGetTime()

Returns the maximum time taken to get a key from the org cache, in nanoseconds.

Signature

public static Long getMaxGetTime()

Return Value

Type: Long

getMaxValueSize()

Deprecated and available only in API versions 49.0 and earlier. Returns the maximum item size for keys in the org cache, in bytes.

Signature

public static Long getMaxValueSize()

Return Value

Type: Long

getMissRate()

Returns the miss rate in the org cache.

Signature

public static Double getMissRate()

Return Value

Type: Double

getName()

Returns the name of the default cache partition.

Signature

public String getName()

Return Value

Type: String

The name of the default cache partition.

getNumKeys()

Returns the total number of keys in the org cache.

Signature

public static Long getNumKeys()

Return Value

Type: Long

getPartition(partitionName)

Returns a partition from the org cache that corresponds to the specified partition name.

Signature

public static cache.OrgPartition getPartition(String partitionName)

Parameters

partitionName
Type: String
A partition name that is qualified by the namespace, for example, namespace.partition.

Return Value

Type: Cache.OrgPartition

Example

After you get the org partition, you can add and retrieve the partition’s cache values.

1// Get partition
2Cache.OrgPartition orgPart = Cache.Org.getPartition('myNs.myPartition');
3// Retrieve cache value from the partition
4if (orgPart.contains('BookTitle')) {
5    String cachedTitle = (String)orgPart.get('BookTitle');
6}
7
8// Add cache value to the partition
9orgPart.put('OrderDate', Date.today());
10
11// Or use dot notation to call partition methods
12String cachedAuthor = (String)Cache.Org.getPartition('myNs.myPartition').get('BookAuthor');

put(key, value)

Stores the specified key/value pair as a cached entry in the org cache. The put method can write only to the cache in your org’s namespace.

Signature

public static void put(String key, Object value)

Parameters

key
Type: String
A case-sensitive string value that uniquely identifies a cached value. For information about the format of the key name, see Usage.
value
Type: Object
The value to store in the cache. The cached value must be serializable.

Return Value

Type: void

put(key, value, visibility)

Stores the specified key/value pair as a cached entry in the org cache and sets the cached value’s visibility.

Signature

public static void put(String key, Object value, Cache.Visibility visibility)

Parameters

key
Type: String
A case-sensitive string value that uniquely identifies a cached value. For information about the format of the key name, see Usage.
value
Type: Object
The value to store in the cache. The cached value must be serializable.
visibility
Type: Cache.Visibility
Indicates whether the cached value is available only to Apex code that is executing in the same namespace or to Apex code executing from any namespace.

Return Value

Type: void

put(key, value, ttlSecs)

Stores the specified key/value pair as a cached entry in the org cache and sets the cached value’s lifetime.

Signature

public static void put(String key, Object value, Integer ttlSecs)

Parameters

key
Type: String
A case-sensitive string value that uniquely identifies a cached value. For information about the format of the key name, see Usage.
value
Type: Object
The value to store in the cache. The cached value must be serializable.
ttlSecs
Type: Integer
The amount of time, in seconds, to keep the cached value in the org cache. The maximum is 172,800 seconds (48 hours). The minimum value is 300 seconds or 5 minutes. The default value is 86,400 seconds (24 hours).

Return Value

Type: void

put(key, value, ttlSecs, visibility, immutable)

Stores the specified key/value pair as a cached entry in the org cache. This method also sets the cached value’s lifetime, visibility, and whether it can be overwritten by another namespace.

Signature

public static void put(String key, Object value, Integer ttlSecs, cache.Visibility visibility, Boolean immutable)

Parameters

key
Type: String
A case-sensitive string value that uniquely identifies a cached value. For information about the format of the key name, see Usage.
value
Type: Object
The value to store in the cache. The cached value must be serializable.
ttlSecs
Type: Integer
The amount of time, in seconds, to keep the cached value in the org cache. The maximum is 172,800 seconds (48 hours). The minimum value is 300 seconds or 5 minutes. The default value is 86,400 seconds (24 hours).
visibility
Type: Cache.Visibility
Indicates whether the cached value is available only to Apex code that is executing in the same namespace or to Apex code executing from any namespace.
immutable
Type: Boolean
Indicates whether the cached value can be overwritten by another namespace (false) or not (true).

Return Value

Type: void

remove(key)

Deletes the cached value corresponding to the specified key from the org cache.

Signature

public static Boolean remove(String key)

Parameters

key
Type: String
A case-sensitive string value that uniquely identifies a cached value. For information about the format of the key name, see Usage.

Return Value

Type: Boolean

true if the cache value was successfully removed. Otherwise, false.

remove(cacheBuilder, key)

Deletes the cached value corresponding to the specified key from the org cache. Use this method if your cached value is a class that implements the CacheBuilder interface.

Signature

public static Boolean remove(System.Type cacheBuilder, String key)

Parameters

cacheBuilder
Type: System.Type
The Apex class that implements the CacheBuilder interface.
key
Type: String
A case-sensitive string value that, combined with the class name corresponding to the cacheBuilder parameter, uniquely identifies a cached value.

Return Value

Type: Boolean

true if the cache value was successfully removed. Otherwise, false.