Cyber Monday Deal : Flat 30% OFF! + free self-paced courses  - SCHEDULE CALL

Understanding The Concept of Cache Namespace Management

Introduction

In this blog, you will learn about the core concepts of cache namespaces, different methods, syntax, and constants through a series of interview questions as a part of your salesforce learning.

Q.1. What does "Cache Namespace" Mean? What Classes are Offered Under it?

Ans: Methods for controlling the platform cache are available in the Cache namespace.

The classes in the Cache namespace are listed below:

  • CacheBuilder Interface
  • Org Class
  • OrgPartition Class
  • Partition Class
  • Session Class
  • SessionPartition Class
  • Cache Exceptions
  • Visibility Enum

The above classes contain their respective methods, constructors, and enums used in various sections.

Q.2. What is The Cache Builder interface? Use an Example to Demonstrate.

Ans: The CacheBuilder interface is an interface for safely retrieving and removing values from a session or org cache. Use the interface to generate a value you want to be stored in the cache. The interface checks for cache misses, so you no longer need to check for null cache values yourself. It has the namespace of Auth.

In this example, the CacheBuilder interface is implemented by a class called UserInfoCache. The class caches the SOQL query's results against the User object.

class UserinfoCache implements Cache. CacheBuilder {
public Object doLoadString userid) {
User u = (User [SELECT Id, IsActive, username FROM User WHERE id
return u;
]
]

This example retrieves a cached user record based on a user ID. The value is returned if it is present in the org cache. The doLoad(String var) method is repeated if the value is missing, and the new value is cached and returned.

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

Q.3. What are The Available Methods in The Cache Builder Interface?

Ans: The CacheBuilder interface has a single method:

Method

Description

Signature

Parameters

Return Value

doLoad(var)

It contains the reasoning behind creating a cached value. You don't directly call this method. Instead, it is indirectly invoked when the class that implements the CacheBuilder interface is referenced.


 

public Object doLoad(String var)


 

var

Type: String

Type: Object


 

Q.4. What is an Org Class? Mention its Usage.

Ans: To add, retrieve, and manage values in the org cache, use the Cache.Org class. In contrast to the session cache, the organization cache is accessible to the organization across requests and to all users. It is also not associated with any session. It has the namespace of Cache.

Usage: 

Cache Key Format

The format of the primary parameter that various methods in this class, like put, get, and contains, accept, are listed in the following table.

Key Format Description
Namespace. part tion. koy    Ful qalfied ey ame.
Roy tes 03 partion mahed as dealt when the
namespace. paze tion pexisomited
Local partieion. key

Usethe Loca. prefix fer tothe g's ramespace when the
orgdossn'thave: namespace defo ihecrg asa namespace
defined, the Local prefix aso refers to that rg's amespice.

Note:

  • A caching method without qualifying the key name results in Cache.Org.OrgCacheException being thrown and raised if no default partition is declared in the org.
  •  The local prefix in an installed managed package corresponds to the subscriber org's namespace, not the package's. Cache-put requests cannot be made in a partition that the calling class does not control.

Q.5. Illustrate an Example for an Org Class.

Ans: The controller for a sample Visualforce page is the Org class (shown in the subsequent code sample). The init() method, which the Visualforce page calls when it loads using the action attribute, adds the cached settings for the first time—the namespace. The partition prefix does not appear in the cache keys. They all refer to the organization's default partition. Create a partition and set it as the default to run this sample.

  • There are four output components on the Visualforce page. 
  • The following values are returned from the cache by the get methods that these components call on the controller: a date, data from the MyData inner class, a counter, a text value, and a list. The list's size is also reported.
  • Two buttons are also present on the Visualforce page. 
  • The Rerender button calls the go() method on the controller. 
  • This technique gives the counter and the custom data in the cache higher values. The two counters rise by one each time you click Rerender.
  •  The go() method reads these counters' values out of the cache, increases them by one, and then places them back in the cache.
  • The date-time value (with key datetime) is removed from the cache by pressing the Remove datetime Key button. As a result, the page's Cached datetime: value is cleared.
public class OrgCacheController ( //Inner class.
// Used as the data type of a cache value.
class MyData (
public String value get; set; }
public Integer counter { get; set; }
public MyData String value) {
this.value value;
this.counter = 0;
}
public void inc(){
counter++;
}
override public String toString() {
return this.value+":"+this.counter;
// Apex List
// Used as the data type of a cached value.
private List numbers
new List("ONE', 'TWO, 'THREE', 'FOUR', 'FIVE'];
// Constructor of the controller for the Visualforce page.
public OrgCacheController(){
}
Adds various values to the cache.
//This method is called when the Visualforce page loads.
public void init(){
All key values are not qualified by the namespace.partition.
// prefix because they use the default partition.
// Add counter to the cache with initial value of 0
// or increment it if it's already there.
if (ICache.Org.contains('counter')){
}
}
Cache.Org.put('counter', 0);
else (
Cache.Org.put('counter', getCounter()+1);
}
// Add the datetime value to the cache only if it's not already there.
if (!Cache.Org.contains('datetime']) {
DateTime dt = DateTime.now();
Cache.Org.put('datetime', dt);
// Add the custom data to the cache only if it's not already there.
(Cache.Org.contains('data')){
Cache.Org.put('data', new MyData('Some custom value"));
// Add a list of number to the cache if not already there.
[Cache.Org.contains('list')){
Cache.Org.put('list', numbers);
}
// Add a string value to the cache if not already there.
if (!Cache.Org.contains('output')){
Cache.Org.put('output', 'Cached text value');
}
// Return counter from the cache.
public Integer getCounter() {
return (Integer|Cache.Org.get('counter');
]
}
}
}
Return datetime value from the cache.
public String getCachedDatetime() {
DateTime dt-(DateTime)Cache.Org.get('datetime");
return dt = null ? dt.format(): null;
// Return cached value whose type is the inner class MyData.
public String getCachedData(){
MyData mydata (MyData]Cache.Org.get('data');
return mydata != null ? mydata.toString(): null;
// Return output from the cache.
public String getOutput() {
return (String)Cache.Org.get('output");
// Return list from the cache.
public List getList() {
return (List|Cache.Org.get('list');
}
// Method invoked by the Rerender button on the Visualforce page.
// Updates the values of various cached values.
// Increases the values of counter and the MyData counter if those
// cache values are still in the cache.
public PageReference go() {
//Increase the cached counter value or set it to 0 J/if it's not cached.
if (Cache.Org.contains('counter']} {
Cache.Org.put('counter', getCounter() + 1);
} else {
Cache.Org.put('counter', 0);
}
// Get the custom data value from the cache.
MyData d = (MyDataCache.Org.get('data');
// Only if the data is already in the cache, update it.
if (Cache.Org.contains('data']) {
d.inc();
Cache.Org.put('data', d);
}
}
}
return null;
// Method invoked by the Remove button on the Visualforce page.
// Removes the datetime cached value from the org cache.
public Page Reference remove() {
Cache.Org.remove('datetime');
return null;
}

This is the OrgCacheController class's corresponding Visualforce page.


Cached datetime: 

Cached data: 

Cached counter: 

Repeat: 
8nbsp;

List size: 




gol” valu
mmandButton

“(Iremove]" value="Remove datetime Key"
rerender="output'/>

This is the result of pressing twice the Rerender button on the website. If a key with the name counter was already in the cache when this sample was run, the counter value might be different in your situation.



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

Q.6. What are The Org Constants and Methods?

Ans: You can use an Org class constant to set 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.

Below are some of the methods of the Org class that are all static.

Methods

Description

Signature

Parameters

Return Value

contains(key)

It returns true if the supplied key corresponds to a cached value in the org cache.

public static Boolean contains(String key)

key

Type: String

Type: Boolean

contains(keys)

It returns true if the provided key items have values in the org cache.

public static List contains(List keys)

keys

Type: List

Type: List

contains(set OfKeys)

It returns true if the supplied set of keys' values are in the org cache.

public static Map contains (Set keys)

setOfKeys

Type: Set

Type: Map

get(key)

It returns the cached value from the org cache corresponding to the given key.

public static Object get(String key)

key

Type: String

Type: Object

get(cacheBuilder, key)

It returns the cached value from the org cache corresponding to the given key. Use this method if the class representing your cached item implements the Cache Builder interface.

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

cacheBuilder

Type: System.Type

 

key

Type: String

Type: Object

get(keys)

It returns the cached values corresponding to the given set of keys from the org cache.

public static Map get (Set keys)

keys

Type: Set

Type: Map

getAvgGetSize()

It gives back, in bytes, the average item size of all the keys retrieved from the org cache.

public static Long getAvgGetSize()

 

Type: Long

getAvgGetTime()

It gives the average amount of time, in nanoseconds, needed to retrieve a key from the org cache.

public static Long getAvgGetTime ()

 

Type: Long

getAvgValueSize()

It is only supported in API versions 49.0 and earlier; it is deprecated. It gives the average item size, in bytes, for keys in the org cache.

public static Long getAvgValueSize()

 

Type: Long

getCapacity()

It returns the amount of the org cache capacity that has been utilized.

public static Double getCapacity()

 

Type: Double

getKeys()

It returns a list of all keys accessible to the calling namespace and kept in the org cache.

public static Set getKeys()

 

Type: Set

getMaxGet Size()

It gets the largest item size, in bytes, for all the keys that were retrieved from the org cache.

public static Long getMaxGetSize ()

 

Type: Long

getMaxGetTime()

It gives the maximum amount of time, in nanoseconds, needed to retrieve a key from the org cache.

public static Long getMaxGetTime()

 

Type: Long

getMaxValue Size()

It is only supported in API versions 49.0 and earlier; it is deprecated. The maximum item size for keys in the org cache is returned, expressed in bytes.

public static Long getMaxValue Size()

 

Type: Long

getMissRate()

The miss rate in the org cache is returned.

public static Double getMissRate()

 

Type: Double

getName()

It gives the default cache partition's name back.

public String getName()

 

Type: String

getNumKeys()

The entire number of keys in the org cache is returned.

public static Long getNumKeys()

 

Type: Long

getPartition (partitionName)

It returns the partition with the supplied partition name from the org cache.

public static cache.Org Partition getPartition (String partitionName)

partitionName

Type: String

Type: Cache.OrgPartition

put(key, value)

It creates a cached item for the given key/value pair in the organization cache. Only the cache in your org's namespace can be written to using the put method.

public static void put(String key, Object value)

key

Type: String

 

value

Type: Object

Type: void

put(key, value, visibility)

It sets the visibility of the cached value and stores the supplied key/value pair as a cached entry in the organization cache.

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

key

Type: String

 

value

Type: Object

 

visibility

Type: Cache.Visibility

Type: void

put(key, value, ttlSecs)

It sets the lifespan of the cached value and stores the supplied key/value pair as a cached entry in the organization cache.

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

key

Type: String

 

value

Type: Object

 

ttlSecs

Type: Integer

Type: void

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

It creates a cached item for the given key/value pair in the organization cache. Additionally, this approach modifies the lifetime, visibility, and  whether another namespace has the ability to replace it.

public static void put(String key, Object value, Integer ttlSecs, cache. Visibility

visibility, Boolean immutable)

key

Type: String

 

value

Type: Object

 

ttlSecs

Type: Integer

 

visibility

Type: Cache.Visibility

 

immutable

Type: Boolean

Type: void

remove(key)

It removes the cached value associated with the given key from the org cache.

public static Boolean remove(String key)

key

Type: String

Type: Boolean

remove(cache Builder, key)

It removes the cached value associated with the given key from the org cache. If the class representing your cached item implements the CacheBuilder interface, use this method.

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

cacheBuilder

Type: System. Type

 

key

Type: String

Type: Boolean

Q.7. What is The Org Partition class? What is it Used for?

Ans: OrgPartition contains tools for managing the cache values in a particular partition's org cache. Unlike the session cache, the org cache is not connected to any session. It is accessible to all users and the organization across requests. It has the namespace "Cache."


 

Usage:

  • All of the non-static methods from Cache. Partition, which this class extends, is inherited. 
  • Essential creation and validation utility methods are not supported and can only be called from the Cache—partition parent class. 
  • Make a Cache.Org.getPartition call to acquire an org partition and enter the following fully qualified partition name.

Learn more about Partition Methods for a list of Cache—partition methods by joining our online Salesforce training courses.

Q.8. What is The Partition Class? What is The Format for Partition Methods?

Ans: The Partition class is the base class for the partition types Cache.Org and Cache. Session. Use the subclasses to manage the cache partition for org and session caches. 

Cache Key Format for Partition Methods:

The key name is required by the methods to add, retrieve, and manage cache values in a partition after obtaining the partition object (an instance of Cache.OrgPartition or Cache.SessionPartition)—the namespace. A partition prefix is not part of the critical name you pass to these methods (get(), put(), delete(), and contains()).

Q.9. What are The Methods of The Partition Class?

Ans: Below are some of the methods of the partition class.

Methods

Description

Signature

Parameters

Return Value

contains(key)

If the cache partition has a cached value matching the supplied key, then the function returns true.

public Boolean contains(String key)

key

Type: String

Type: Boolean

contains(set OfKeys)

It returns true if the supplied set of keys' values is present in the cache partition.

public Map contains (Set keys)

setOfKeys

Type: Set

Type: Map

createFully QualifiedKey (namespace, partition, key)

It creates a fully qualified key from the key components that have been handed in. namespace. partition. key is the format of the key string that is generated.

public static String createFully QualifiedKey (String namespace, String partition, String

key)

namespace

Type: String

 

partition

Type: String

 

key

Type: String

Type: String

createFully Qualified Partition( namespace, partition)

It creates a fully qualified partition name using the namespace and partition supplied as arguments. The resulting partition string has the namespace. partition format.

public static String createFully Qualified Partition(String namespace, String partition)

namespace

Type: String

 

partition

Type: String

Type: String

get(key)

It returns the cached value from the cache partition that corresponds to the given key.

public Object get(String key)

key

Type: String

Type: Object

get(keys)

It returns from the cache partition the cached values corresponding to the given set of keys.

public Map get (Set keys)

keys

Type: Set

Type: Map

get(cacheBuilder, key)

The partition cache's cached value that corresponds to the given key is returned. Use this method if the class representing your cached item implements the CacheBuilder interface.

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

cacheBuilder

Type: System. Type

 

key

Type: String

Type: Object

getAvgGetSize()

It gives back, in bytes, the average item size of all the keys retrieved from the cache partition.

public Long getAvgGetSize()

 

Type: Long

getAvgGetTime ()

It gives the average amount of time, in nanoseconds, needed to retrieve a key from the cache partition.

public Long getAvgGetTime ()

 

Type: Long

getAvgValueSize()

It is only supported in API versions 49.0 and earlier; it is deprecated. It gives the average item size, in bytes, for keys in the cache partition.

public Long getAvgValueSize()

 

Type: Long

getCapacity()

It returns the percentage of the cache partition capacity that has been utilized.

public Double getCapacity()

 

Type: Double

getKeys()

It returns a list of all keys that are accessible to the calling namespace and kept in the cache partition.

public Set getKeys()

 

Type: Set

getMaxGet Size()

It gets the largest item size, in bytes, for all the keys that were retrieved from the cache partition.

public Long getMaxGetSize ()

 

Type: Long

getMaxGetTime()

It gives the maximum amount of time, in nanoseconds, needed to retrieve a key from the org cache.

public Long getMaxGetTime()

 

Type: Long

getMaxValue Size()

It is only supported in API versions 49.0 and earlier; it is deprecated. The maximum item size for keys in the cache partition is returned, expressed in bytes.

public Long getMaxValue Size()

 

Type: Long

getMissRate()

The miss rate in the cache partition is returned.

public Double getMissRate()

 

Type: Double

getName()

It gives the default cache partition's name back.

public String getName()

 

Type: String

getNumKeys()

The entire number of keys in the cache partition is returned.

public Long getNumKeys()

 

Type: Long

isAvailable()

If the Salesforce session is available, the return value is true. It applies only to Cache. SessionPartition. When an active session isn't present, such as in asynchronous Apex or code called by asynchronous Apex, the session cache isn't accessible. For instance, when an Apex trigger operates in an asynchronous context, the session cache is not accessible if batch Apex causes the trigger to fire.

public Boolean isAvailable()

 

Type: Boolean

put(key, value)

It creates a cached item for the given key/value pair in the cache partition. Only the cache in your org's namespace can be written to using the put method.

public void put(String key, Object value)

key

Type: String

 

value

Type: Object

Type: void

put(key, value, visibility)

It sets the visibility of the cached value and stores the supplied key/value pair as a cached entry in the cache partition.

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

key

Type: String

 

value

Type: Object

 

visibility

Type: Cache.Visibility

Type: void

put(key, value, ttlSecs)

It sets the lifespan of the cached value and stores the supplied key/value pair as a cached entry in the cache partition.

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

key

Type: String

 

value

Type: Object

 

ttlSecs

Type: Integer

Type: void

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

It creates a cached item for the given key/value pair in the cache partition. Additionally, this approach modifies the lifetime, visibility, and  whether another namespace has the ability to replace it.

public void put(String key, Object value, Integer ttlSecs, cache.Visibility

visibility, Boolean immutable)

key

Type: String

 

value

Type: Object

 

ttlSecs

Type: Integer

 

visibility

Type: Cache.Visibility

 

immutable

Type: Boolean

Type: void

remove(key)

It removes from the cache partition the cached value associated with the given key.

public Boolean remove(String key)

key

Type: String

Type: Boolean

remove(cache Builder, key)

It removes from the cache partition the cached value associated with the given key. Use this method if the class representing your cached item implements the CacheBuilder interface.

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

cacheBuilder

Type: System.Type

 

key

Type: String

Type: Boolean

validate CacheBuilder (cacheBuilder)

It determines whether the supplied class actually implements the CacheBuilder interface.

public static void validateCache Builder(System.Type cacheBuilder)

cacheBuilder

Type: System.Type

Type: 

void

validateKey (isDefault, key)

It verifies a cache key. The Cache throws a method.InvalidParamException procedure  n if the key is invalid A valid key has alphanumeric characters and is not null.

public static void validateKey(Boolean isDefault, String key)

isDefault

Type: Boolean

 

key

Type: String

Type: void

validateKey Value(isDefault, key, value)

It checks to see if a cache key is valid and that the cache value is not null. A Cache. This procedure throws an invalid ParamException procedure. If the key or value is invalid, a InvalidParam Exception will be thrown. A valid key has alphanumeric characters and is not null.

public static void validateKey Value(Boolean isDefault, String key, Object value)

isDefault

Type: Boolean

 

key

Type: String

 

value

Type: Object

Type: void

validateKeys(isDefault, keys)

The supplied cache keys are verified. A Cache.Invalid ParamException has thrown if the key is invalid. A valid key has alphanumeric characters and is not null.

public static void validateKeys (Boolean isDefault, Set keys)

isDefault

Type: Boolean

 

keys

Type: Set

Type: void

validatePartitionName(name)

It ensures, for instance, that the partition name is valid and not null.

public static void validatePartitionName(String name)

name

Type: String

Type: void

Q.10. What is The Session Class? What is The Format for Session Methods?

Ans: Use the Cache- session class to store, access, and manage values in the session cache. As long as the user's Salesforce session is active, the session cache will be active (the user is logged in, and the session has not expired).

Cache Key Format for Session Methods:

The format of the primary parameters that various methods in this class, like put, get, and contains, accept, are listed in the following table.

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.

Note:

  •  A caching method without qualifying the key name throws a Cache.Session.SessionCacheException if there is no default partition set in the org. 
  • The namespace of the subscriber org, not the package's, is referenced by the local prefix in an installed managed package. 
  • Cache put requests are not permitted in a partition the calling class does not possess.

Q.11. Provide an Example for The Session Class.

Ans: The controller for a sample Visualforce page is the Session class (shown in the subsequent code sample). The init() method, which the Visualforce page calls when it loads using the action attribute, adds the cached settings for the first time—the namespace. The partition prefix does not appear in the cache keys. They all refer to the organization's default partition. The myPartition partition is what the Visualforce page anticipates. Create a default partition in your organization called "myPartition" and execute this sample from there.

There are four output components on the Visualforce page. 

  • The get methods on the controller that return date, information based on the MyData inner class, and a counter are called by the first three components. 
  • The cached output key's cached string value is obtained by the following output component using the global variable $ Cache.Session. The $ Cache is next. 
  • Session global variable is used once more in the Visualforce page to loop through the List-type elements of a cached value. The list's size is also reported.

Two buttons are also present on the Visualforce page.

  • The Rerender button calls the go() method on the controller. 
  • This technique gives the counter, and the custom data in the Cache are given higher values. Each time you click "Rerender," one is added to each count. 
  • The go() method reads these counters' values out of the Cache, increases them by one, and then places them back in the Cache.
  • The date-time value (with key datetime) is removed from the Cache by pressing the Remove button. As a result, the page's Cached datetime: value is cleared.
public class SessionCacheController { //Inner class.
// Used as the data type of a cache value.
class MyData (
public String value get; set; }
public Integer counter { get; set; }
public MyData String value) {
this.value value;
this.counter = 0;
}
public void inc(){
counter++;
}
override public String toString() {
return this.value+":"+this.counter;
// Apex List
// Used as the data type of a cached value.
private List numbers-
new List("ONE', 'TWO, 'THREE', 'FOUR', 'FIVE'];
// Constructor of the controller for the Visualforce page.
public SessionCacheController() {
}
Adds various values to the cache.
//This method is called when the Visualforce page loads.
public void init(){
// All key values are not qualified by the namespace.partition
// prefix because they use the default partition.
// Add counter to the cache with initial value of 0
// or increment it if it's already there.
if (ICache.Session.contains('counter')){
}
1
}
Cache.Session.put('counter', 0);
else (
Cache.Session.put('counter', getCounter()+1);
// Add the datetime value to the cache only if it's not already there.
if (!Cache.Session.contains("datetime")){
DateTime dt = DateTime.now();
Cache.Session.put("datetime", dt);
// Add the custom data to the cache only if it's not already there.
(Cache.Session.contains('data')){
Cache.Session.put('data', new MyData("Some custom value')]:
// Add a list of number to the cache if not already there.
[Cache.Session.contains(list')){
Cache.Session.put('list', numbers);
}
// Add a string value to the cache if not already there.
if (!Cache.Session.contains('output')){
Cache.Session.put('output', 'Cached text value');

// Return counter from the cache.
public Integer getCounter() {
return (Integer|Cache.Session.get('counter');
Return datetime value from the cache.
public String getCachedDatetime() {
DateTime dt-(DateTime)Cache.Session.get('datetime");
return dt != null ? dt.format(): null;
// Return cached value whose type is the inner class MyData.
public String getCachedData(){
MyData mydata (MyData)Cache.Session.get('data'];
return mydata != null ? mydata.toString(): null;
}
// Method invoked by the Rerender button on the Visualforce page.
// Updates the values of various cached values.
// Increases the values of counter and the MyData counter if those
// cache values are still in the cache.
public PageReference go()
//Increase the cached counter value or set it to 0
Jif it's not cached.
if (Cache.Session.contains('counter')){
Cache.Session.put('counter', getCounter()+1):
}else{
Cache Session.put('counter', 0);
// Get the custom data value from the cache.
// Return counter from the cache.
public Integer getCounter() {
return (Integer|Cache.Session.get('counter');
Return datetime value from the cache.
public String getCachedDatetime() {
DateTime dt-(DateTime)Cache.Session.get('datetime");
return dt != null ? dt.format(): null;
// Return cached value whose type is the inner class MyData.
public String getCachedData(){
MyData mydata (MyData)Cache.Session.get('data'];
return mydata != null ? mydata.toString(): null;
}
// Method invoked by the Rerender button on the Visualforce page.
// Updates the values of various cached values.
// Increases the values of counter and the MyData counter if those
// cache values are still in the cache.
public PageReference go()
//Increase the cached counter value or set it to 0
Jif it's not cached.
if (Cache.Session.contains('counter')){
Cache.Session.put('counter', getCounter()+1):
}else{
Cache Session.put('counter', 0);
// Get the custom data value from the cache.

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



Cached datetime: 
Cached data: 
Cached counter: 
Output: 
Repeat: 
 

List size: 

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.

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

Propel your Salesforce training certification to new heights with JanBask Training's industry-leading certification tracks.

Q.12. What are The Session Constants and Methods?

Ans: You can use a Session class constant to set 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 session cache.

Below are some of the methods of the Session class that are all static.

Methods

Description

Signature

Parameters

Return Value

contains(key)

It returns true if the supplied key corresponds to a cached value in the session cache.

public static Boolean contains(String key)

key

Type: String

Type: Boolean

contains(set OfKeys)

It returns true if the supplied set of keys' values are present in the  cache.

public static Map contains (Set keys)

setOfKeys

Type: Set

Type: Map

get(key)

It returns the cached value from the session cache that corresponds to the given key.

public static Object gets (String key)

key

Type: String

Type: Object

get(cacheBuilder, key)

It returns the cached value from the session cache corresponding to the given key. Use this method if the class representing your cached item implements the Cache Builder interface.

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

cacheBuilder

Type: System.Type

 

key

Type: String

Type: Object

get(keys)

It returns the cached values corresponding to the given set of keys from the session cache.

public static Map get (Set keys)

keys

Type: Set

Type: Map

getAvgGetSize()

It gives back, in bytes, the average item size of all the keys retrieved from the session  cache.

public static Long getAvgGetSize()

 

Type: Long

getAvgGetTime ()

It gives the average amount of time, in nanoseconds, needed to retrieve a key from the session cache.

public static Long getAvgGetTime ()

 

Type: Long

getAvgValueSize()

It is only supported in API versions 49.0 and earlier; it is deprecated. It gives the average item size, in bytes, for keys in the session cache.

public static Long getAvgValueSize()

 

Type: Long

getCapacity()

It returns the percentage of the session  cache capacity that has been utilized.

public static Double getCapacity()

 

Type: Double

getKeys()

It returns a list of all keys that are accessible to the calling namespace and kept in the session cache.

public static Set getKeys()

 

Type: Set

getMaxGet Size()

It gets the largest item size, in bytes, for all the keys that were retrieved from the session  cache.

public static Long getMaxGetSize ()

 

Type: Long

getMaxGetTime()

It gives the maximum amount of time, in nanoseconds, needed to retrieve a key from the session  cache.

public static Long getMaxGetTime()

 

Type: Long

getMaxValue Size()

It is only supported in API versions 49.0 and earlier; it is deprecated. The maximum item size for keys in the session  cache is returned, expressed in bytes.

public static Long getMaxValue Size()

 

Type: Long

getMissRate()

The miss rate in the session  cache is returned.

public static Double getMissRate()

 

Type: Double

getName()

It gives the default cache partition's name back.

public String getName()

 

Type: String

getNumKeys()

The entire number of keys in the session  cache is returned.

public static Long getNumKeys()

 

Type: Long

getPartition (partitionName)

It returns the partition with the supplied partition name from the session  cache.

public static cache.Org Partition getPartition (String partitionName)

partitionName

Type: String

Type: Cache.OrgPartition

isAvailable()

If the session cache is accessible, it will return true. When there isn't an active session present, as in situations like

code called by asynchronous Apex or asynchronous Apex. For instance, if batch Apex triggers an Apex execution, the session

Considering that the trigger operates in an asynchronous environment, the cache is not accessible in the trigger.

public static Boolean isAvailable()

 

Type: Boolean

put(key, value)

It creates a cached item for the given key/value pair in the session  cache. Only the cache in your org's namespace can be written to using the put method.

public static void put(String key, Object value)

key

Type: String

 

value

Type: Object

Type: void

put(key, value, visibility)

It sets the visibility of the cached value and stores the supplied key/value pair as a cached entry in the session  cache.

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

key

Type: String

 

value

Type: Object

 

visibility

Type: Cache.Visibility

Type: void

put(key, value, ttlSecs)

It sets the lifespan of the cached value and stores the supplied key/value pair as a cached entry in the organization cache.

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

key

Type: String

 

value

Type: Object

 

ttlSecs

Type: Integer

Type: void

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

It creates a cached item for the given key/value pair in the session  cache. Additionally, this approach modifies the lifetime, visibility, and  whether another namespace has the ability to replace it.

public static void put(String key, Object value, Integer ttlSecs, cache.Visibility

visibility, Boolean immutable)

key

Type: String

 

value

Type: Object

 

ttlSecs

Type: Integer

 

visibility

Type: Cache.Visibility

 

immutable

Type: Boolean

Type: void

remove(key)

It removes from the session  cache the cached value associated with the given key.

public static Boolean remove(String key)

key

Type: String

Type: Boolean

remove(cache Builder, key)

It removes from the session  cache the cached value associated with the given key. Use this method if the class representing your cached item implements the CacheBuilder interface.

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

cacheBuilder

Type: System.Type

 

key

Type: String

Type: Boolean

Q.13. What is The Session Partition class? What is it used for?

Ans: Session Partition class contains tools for managing the cache values in a partition's session cache. It has the namespace of Cache.

Usage:

  • All of the non-static methods from Cache. Partition, which this class extends, is inherited. 
  • Essential creation and validation utility methods are not supported and can only be called from the Cache—partition parent class. 
  • Make a Cache.Session.getPartition call to acquire a session partition and enter the following fully qualified partition name.
Cache.SessionPartition sessionPartition =
Cache.Session.getPartition ('namespace.myPartition');

Q.14. Give an Example for The Session Partition Controller class.

Ans: The controller for a sample Visualforce page is contained in this class (shown in the subsequent code sample). The controller provides instructions for using the Cache.SessionPartition methods control a cache value on a specific partition. The controller receives the partition name, counter key name, and initial counter value inputs from the Visualforce page. For these, the controller contains default inputs. The go() method is called, and the counter is increased by one when you click Rerender on the Visualforce page. The counter Key is removed from the Cache when you click Remove Key. When it is added again to the Cache, the counter value is reset to its initial value.

public class SessionPartitionController (
Name of a partition in the local namespace
String partitioninput 'localmyPartition';
// Name of the key
String counterKeyInput = 'counter';
// Key initial value
Integer counterinitValue = 0;
Session partition object
Cache SessionPartition sessionPartition
//Constructor of the controller for the Visualforce page.
public SessionPartitionController() {
}
// Adds counter value to the cache.
// This method is called when the Visualforce page loads.
public void init(){
// Create the partition instance based on the partition name
sessionPartition = getPartition[]:
// Add counter to the cache with an initial value
// or increment it if it's already there.
if (IsessionPartition.contains(counterKeyInput)){
sessionPartition.put(counterKeyInput, counterinitValue);
} else {
sessionPartition.put(counterKeyInput, getCounter() + 1);
}
// Returns the session partition based on the partition name
// given in the Visualforce page or the default value.
private Cache.SessionPartition getPartition(){
if (sessionPartition == null) {
sessionPartition Cache Session.getPartition(partitionInput);
]
return sessionPartition:
1
// Return counter from the cache.
public Integer getCounter() {
return (Integer getPartition().get(counterKeyinput);
//Invoked by the Submit button to save input values
// supplied by the user.
public PageReference save() {
// Reset the initial key value in the cache
getPartition().put(counterKeyInput, counterInitValue);
return null;
// Method invoked by the Rerender button on the Visualforce page.
// Updates the values of various cached values.
// Increases the values of counter and the MyData counter if those
// cache values are still in the cache.
public PageReference go() {
Get the partition object
sessionPartition = getPartition();
//Increase the cached counter value or set it to 0
// if it's not cached.
if (sessionPartition.contains(counterKeyInput)) {
sessionPartition.put(counterKeyInput, getCounter() + 1);
else {
sessionPartition.put(counterKeyInput, counterinitValue);
1
]
return null;
Method invoked by the Remove button on the Visualforce page.
// Removes the datetime cached value from the session cache.
public PageReference remove() {
getPartition().remove(counterKeyinput);
return null;
}
}
// Get and set methods for accessing variables
// that correspond to the input text fields on
the Visualforce page.
public String getPartitioninput[] [
return partitioninput;
public String getCounterKeyinput[] {
return counterKeyInput:
}
public Integer getCounterInitValue(){
return counterinitValue;
}
public void setPartitionInput(String partition){
this.partitionInput = partition;
}
sessionPartition.put(counterKeyInput, getCounter() + 1);
else {
sessionPartition.put(counterKeyInput, counterinitValue);
1
]
return null;
Method invoked by the Remove button on the Visualforce page.
// Removes the datetime cached value from the session cache.
public PageReference remove() {
getPartition().remove(counterKeyinput);
return null;
}
}
// Get and set methods for accessing variables
// that correspond to the input text fields on
the Visualforce page.
public String getPartitioninput[] [
return partitioninput;
public String getCounterKeyinput[] {
return counterKeyInput:
}
public Integer getCounterInitValue(){
return counterinitValue;
}
public void setPartitionInput(String partition){
this.partitionInput = partition;
}

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



Partition with Namespace Prefix:  
Counter Key Name: 
Counter Initial Value: 
Cached Counter: 





Q.15. List some of The Cache Exceptions.

Ans: Exception classes can be found in the Cache namespace.

All exception classes include built-in methods to return the exception type and error message. These exceptions in the table below are present in the Cache namespace.

Exception Thrown When
Cache.Session.  An error occurred while adding or retrieving a value in the session cache.
SessionCacheException Cache.session.SessionCacheNoSessionException An attempt is made to access the cache when the session cache isn't available.

 

Q.16. What is a Visibility Enum? Mention Some of its Values.

Ans: To specify whether a cached item is visible across all namespaces or just the value's namespace, use the Cache. Visibility enumeration in the Cache.Session or Cache.Org methods.

The values of the Cache. The visibility enum is as follows:

Value Description
ALL The cached value is available to Apex code executing from any namespace. This is the default state.
NAMESPACE The cached value is available to Apex code executing from the same namespace.
If a key has the visibility.NAMESPACE attribute, a get method initiated from a different namespace returns null.

Conclusion

Cache Namespace Management in the context of Salesforce generally refers to the management of cached data within a specific namespace or for a managed package. Hope these interview questions and answers related to Cache Namespace Management have helped you learn about the concept. 

Trending Courses

Cyber Security

  • Introduction to cybersecurity
  • Cryptography and Secure Communication 
  • Cloud Computing Architectural Framework
  • Security Architectures and Models

Upcoming Class

2 days 14 Dec 2024

QA

  • Introduction and Software Testing
  • Software Test Life Cycle
  • Automation Testing and API Testing
  • Selenium framework development using Testing

Upcoming Class

8 days 20 Dec 2024

Salesforce

  • Salesforce Configuration Introduction
  • Security & Automation Process
  • Sales & Service Cloud
  • Apex Programming, SOQL & SOSL

Upcoming Class

2 days 14 Dec 2024

Business Analyst

  • BA & Stakeholders Overview
  • BPMN, Requirement Elicitation
  • BA Tools & Design Documents
  • Enterprise Analysis, Agile & Scrum

Upcoming Class

2 days 14 Dec 2024

MS SQL Server

  • Introduction & Database Query
  • Programming, Indexes & System Functions
  • SSIS Package Development Procedures
  • SSRS Report Design

Upcoming Class

1 day 13 Dec 2024

Data Science

  • Data Science Introduction
  • Hadoop and Spark Overview
  • Python & Intro to R Programming
  • Machine Learning

Upcoming Class

2 days 14 Dec 2024

DevOps

  • Intro to DevOps
  • GIT and Maven
  • Jenkins & Ansible
  • Docker and Cloud Computing

Upcoming Class

5 days 17 Dec 2024

Hadoop

  • Architecture, HDFS & MapReduce
  • Unix Shell & Apache Pig Installation
  • HIVE Installation & User-Defined Functions
  • SQOOP & Hbase Installation

Upcoming Class

8 days 20 Dec 2024

Python

  • Features of Python
  • Python Editors and IDEs
  • Data types and Variables
  • Python File Operation

Upcoming Class

9 days 21 Dec 2024

Artificial Intelligence

  • Components of AI
  • Categories of Machine Learning
  • Recurrent Neural Networks
  • Recurrent Neural Networks

Upcoming Class

2 days 14 Dec 2024

Machine Learning

  • Introduction to Machine Learning & Python
  • Machine Learning: Supervised Learning
  • Machine Learning: Unsupervised Learning

Upcoming Class

15 days 27 Dec 2024

Tableau

  • Introduction to Tableau Desktop
  • Data Transformation Methods
  • Configuring tableau server
  • Integration with R & Hadoop

Upcoming Class

8 days 20 Dec 2024