Sunday, May 19, 2019

Salesforce Interview Questions On Batch Apex Updated 2024

1) What is batch apex in salesforce? 

 As platform limits play a very important role in Salesforce, it becomes more important to stay within the platform limits when dealing with large numbers of records. With batch apex, we can process a large number of records asynchronously.

Understanding batch apex with an example would be easier. Let’s try to understand it with a scenario described below.

Let’s say you want to process 1 million records using Batch Apex. The execution logic of the batch class is called once for each batch of records you are processing. Each time you invoke a batch class, the job is placed on the Apex job queue and is executed as a discrete transaction. Every transaction starts with a new set of governor limits, making it easier to ensure that your code stays within the governor execution limits. If one batch fails to process successfully, all other successful batch transactions aren’t rolled back.

When we use batch apex, we implement the Database.batchable() interface.

The Database.batchable() interface contains three methods that we need to define inside the batch class, and they are as below:

1) start

2) execute

3) Finish

  • Start method and finish method are called only once inside batch class. 
  • Start method collects the data for processing. 
  • Execute method performs operations. 
  • The order of execution is not guaranteed in execute method.
  • Finish method generally used for sending emails or calling another batch class when the current batch is completed. 
Syntax:

global class batch implements Database.Batchable < sObject > { 

global (Database.QueryLocator or  Iterable<sObject>)

start(Database.BatchableContext bc) { 

//query on object; 

//return Database.getQueryLocator(query); 

global void execute(Database.batchableContext bc, List < SObject > scope) { 

//some processing. 

global void finish(Database.BatchableContext bc) { 

//job such as sending email or calling another batch class 


2) What is database.stateful interface? 

Batch Apex is stateless.  Each execution of a batch Apex job is considered a discrete transaction. If we implements Database.Stateful we can maintained state across transactions. Using Database.Stateful only instance variable holds values static members does not hold values. If we want to count records as batch proceeds maintaining state is important as after one transaction new transaction will start and members will loose their values.

3) How to write Test class for batch class? 

You need to call batch class from inside of test.starttest() and test.stoptest()
with below syntax,

@istest

public class testclass{

static testmethod void methodname1()

{

test.starttest();

batchClassName obj=new batchClassName ();

Id batchId=Database.executeBatch(obj);

test.stoptest();

}

}


4) Explain the concept of scope size in batch apex?

As we know, the default scope size is 200. If no size is specified with the optional scope parameter of Database.executeBatch, Salesforce chunks the records returned by the start method into batches of 200 records. The optional scope parameter of Database.executeBatch can have a maximum value of 2,000.

When an apex job is executed by setting some value for scope size, it is not necessary that the number of records processed in one batch iteration be the same as the scope size specified.

Records from the query locator are retrieved in chunks of the given chunk size, called retrieveChunkSize.

Chunk sizes available are 100, 400, and 2000.

The selection of chunk size depends on the scope size specified.

If 1 <= scopeSize <= 100, then retrieveChunkSize = 100.

If 101 <= scopeSize <= 400, then retrieveChunkSize = 400.

If 401 <= scopeSize <= 2000, then retrieveChunkSize = 2000.

So let's say we have 285 records to be processed and we specify the scope size as 80, then the retrieveChunkSize will be 100.

In this case, the total number of batches will not be 4, i.e., (285/80), but in this case, it would be 3 retrieve chunks and 6 execute chunks, so the total number of batches will be 6.

1. Retrieve chunk 1: retrieve the first 100 records

Execute chunk 1: pass the first 80 records to the execute() method.

Execute chunk 2: pass the remaining 20 records from this retrieve chunk to the execute() method.

2. Retrieve chunk 2: retrieve the next 100 records.

Execute chunk 3: pass the first 80 records to the execute() method.

Execute chunk 4: pass the remaining 20 records from this retrieve chunk to the execute() method.

3. Retrieve chunk 3: retrieve the next 85 records.

Execute chunk 5: pass the first 80 records to the execute() method.

Execute chunk 6: pass the remaining 5 records from this retrieve chunk to the execute() method.


 5) Let say we have 30 records, How many times the executes method will be called for below 2 queries?

A)   updateNameOfAccount obj=new updateNameOfAccount();
       Database.executeBatch(obj);

B)   Final Integer batchsize = 3;
       updateNameOfAccount obj=new updateNameOfAccount();
       Database.executeBatch(obj,batchsize);


In query (A) as batch size is not specified, so by default it will be considered as 200. so retrieve chunks will be 400. All 30 records will be retrieved in single chunk.

so now, 30/200 = 1 batches will be formed and hence execute method will be called 1 time.


In query (B) as the batch size is specified as 3, so retrieve chunk will be 100. All 30 records will be retrieved in single chunk.

so now, 30/3 = 10 batches will be formed and hence execute method will be called 10 times.

6) What is Database.BatchableContext?

All the methods in the Database.Batchable interface require a reference to a Database.BatchableContext object. 

This object is used to track the progress of the batch job.

getJobID returns the ID of the AsyncApexJob object associated with this batch job as a string.

For example,

public void finish(Database.BatchableContext bc){

        AsyncApexJob job = [SELECT Id, Status, NumberOfErrors,

            JobItemsProcessed,

            TotalJobItems, CreatedBy.Email

            FROM AsyncApexJob

            WHERE Id = :bc.getJobId()];

        // call some utility to send email

          Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

         String[] toAddresses = new String[] {'Testabc@gmail.com'};

         mail.setToAddresses(toAddresses);

        mail.setSubject('Batch Status ' + job.Status + 'Record Processed ' + recordsProcessed );

        mail.setPlainTextBody('Total Jobs Processed: ' + job .TotalJobItems +   'with '+ job .NumberOfErrors + ' failures.');

        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

    }

}


7) Can we use public access modifier instead of global access modifier in batch apex?

Yes. When Database.Batchable was first available, implementers had no choice but to use the global access modifier. This error has now been corrected so that you now have the choice of making the Database.Batchable public or global and the public is the right choice most of the time.
global makes a class usable by code outside of a managed package where as public makes a class usable by any class within the managed package or within a non-packaged set of source code.

8) Explain Database.executeBatch Method?
  • Database.executeBatch method is used begin a batch job.
  • When Database.executeBatch method is called Salesforce adds the process to the queue. Actual execution can be delayed and it depends on service availability.
  • It takes 2 parameters as shown in example below,
      updateNameOfAccount obj=new updateNameOfAccount();
      Database.executeBatch(obj,scope);

Where, obj is an instance of a class that implements the Database.Batchable interface and scope is an optional parameter.

Database.executeBatch method returns the ID of the AsyncApexJob object, which we can use for tracking the progress of the job as shown below.

ID batchprocessid = Database.executeBatch(obj);

9) What is the difference between Database.QueryLocator  or  Iterable<sObject> in below statement?

public (Database.QueryLocator | Iterable<sObject>) start(Database.BatchableContext bc) {}

Database.QueryLocator object is used when using a simple query (SELECT) to generate
the scope of objects in the batch job,If we use a QueryLocator object, the governor limit for
the total number of records retrieved by SOQL queries is bypassed. For example, a batch Apex job
for the Account object can return a QueryLocator for all account records (up to 50 million records) in an org. 

Iterable is used to create a complex scope for the batch job. We can also use the iterable to create our own custom process for iterating through the list. The governor limit for the total number of records retrieved by SOQL queries is still enforced using Iterable.

10) Is it possible to do callouts from batch apex?

Yes

11) Which interface need to be implemented in batch class to make callouts from batch apex?

We have to implement the interface Database.AllowsCallouts in batch apex if we want to do callouts from batch apex.

12) Why is it recommended to use Batch Apex only when you have more than one batch of records?

Batch Apex is designed for processing large volumes of records in multiple batches. If there are not enough records to warrant multiple batches, using Queueable Apex might be a more efficient choice.

13) Why can't we pass objects as arguments in the future method?

Object data might change between the time you call the future method and the time it actually executes. and hence we pass the record ID.

14) If downtime occurs and a future method is running, what will happen?

The Future method execution will be rolled back and will restart after downtime overs.

15) If the future method is queued before a service maintenance, what will happen?

It will remain in queue, and when maintenance is over and resources are available, it will be executed.



Looking to Master Batch Apex Essential? Have a look at the course specially designed to Master Batch Apex.


Throughout the course, we'll delve into crucial subjects such as understanding Batch Apex's role, controlling batch size, harnessing the power of Database.Stateful, executing callouts, implementing best practices, exploring limitations, triggering batch classes from apex triggers, mastering future methods, and comprehending queueable Apex. Additionally, we'll discuss advanced concepts like chaining Batch Jobs and dissect real-world scenarios where Batch Apex proves invaluable.

Here's a glimpse of the comprehensive table of contents:

        1) What is Batch Apex in Salesforce?
        2) How to control number of batches in Batch Apex using scope size?
        3) What is Database.Stateful in Batch Apex in Salesforce?
        4) How to do callouts from Batch Apex in Salesforce?
        5) What are Salesforce batch apex best practices?
        6) What are Salesforce batch apex limitations?
        7) How to call batch apex class from apex trigger in Salesforce? 
        8) What is future method in Salesforce?
        9) What is Queueable apex in Salesforce?
      10) Explain chaining of Batch Jobs?
      11) Explain the error "Too many queueable jobs added to the queue"?
      12) Explain the error "Maximum stack depth has been reached"?
      13) Real time scenario for use of Batch Apex?
    

To further enhance your preparation, we've included a dedicated section with 15 more interview questions apart from above, ensuring you're well-equipped to tackle any interview related to Batch Apex.

Get ready to embark on a learning journey that will sharpen your Batch Apex skills and open new doors of opportunity. Enroll now and let's delve into the world of Batch Apex together!


TAGS:  Salesforce Interview Questions on batch apex, Scenario Based Questions on batch Apex, Salesforce interview questions on batch apex for experienced, Salesforce interview questions on batch apex with answers

No comments:

Post a Comment