Sunday, May 19, 2019

Salesforce Interview Questions on batch apex

1) What is batch apex in salesforce? 

 When we want to deal with large number of records we go for batch apex. The code inside batch class runs asynchronously i.e in future context. The governor limit are also more as compared to synchronous code. 

When we use batch apex we implements Database.batchable() interface and we have to include three methods and they are as follows:

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 





For more details visit: Batch class in Salesforce 

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.

For more information visit: Database.Stateful in Batch Apex in Salesforce

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 default scope size is 200 i.e 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.

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

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

Chunks size available are 100,200,400.

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 say if we 285 records to be proceeds and we specify the scope size as 80 than the retrieveChunkSize  will be 100.

In this case the total number of batches will note 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 first 100 records
Execute chunk 1: pass first 80 records to execute() method
Execute chunk 2: pass remaining 20 records from this retrieve chunk to execute() method

2. Retrieve chunk 2: retrieve next 100 records

Execute chunk 3: pass first 80 records to execute() method
Execute chunk 4: pass remaining 20 records from this retrieve chunk to execute() method

3. Retrieve chunk 3: retrieve next 85 records

Execute chunk 5: pass first 80 records to execute() method
Execute chunk 6: pass remaining 5 records from this retrieve chunk to 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

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.

No comments:

Post a Comment