Tuesday, December 3, 2024

Batch Apex, @future methods, and Queueable Apex in Salesforce, along with example interview questions and answers with scenarios.

 

1. Batch Apex

Batch Apex is used to process large volumes of records asynchronously in Salesforce. It divides the records into batches, processes them separately, and ensures governor limits are handled effectively.

Key Points:

  • Implemented using Database.Batchable interface.
  • Can process up to 50 million records.
  • Divides records into chunks (default 200, customizable).
  • Supports start, execute, and finish methods.

Example:

apex code
global class BatchExample implements Database.Batchable<SObject> {
    global Database.QueryLocator start(Database.BatchableContext bc) {
        return Database.getQueryLocator
('SELECT Id, Name FROM Account WHERE Industry = \'Technology\'');
    }

global void execute(Database.BatchableContext bc, List<Account> scope) {
        for (Account acc : scope) {
            acc.Description = 'Updated by Batch Apex';
        }
        update scope;
    }

    global void finish(Database.BatchableContext bc) {
        System.debug('Batch Apex Processing Completed');
    }
}

2. @future Methods

@future methods are used to perform operations asynchronously, typically when an operation is resource-intensive or must avoid affecting user interaction.

Key Points:

  • Marked with the @future annotation.
  • Methods must be static and return void.
  • Cannot accept SObject or collection of SObject as arguments.
  • Use when the operation does not require an immediate response.

Example:

apex code
public class FutureExample {
    @future
 public static void updateContactEmails(Set<Id> contactIds) {
  List<Contact> contacts = 
  [SELECT Id, Email FROM Contact WHERE Id IN :contactIds];
    for (Contact contact : contacts) {
        contact.Email = 'updated@example.com';
        }
        update contacts;
    }
}

3. Queueable Apex

Queueable Apex is similar to @future methods but with more control and flexibility. It supports complex data types and chaining jobs.

Key Points:

  • Implements the Queueable interface.
  • Allows you to chain jobs.
  • Supports job monitoring through the AsyncApexJob table.
  • Useful for scenarios where @future is insufficient.

Example:

apex code

public class QueueableExample implements Queueable {

    private List<Id> accountIds;

    public QueueableExample(List<Id> accountIds) {

        this.accountIds = accountIds;

    }

public void execute(QueueableContext context) {

   List<Account> accounts = 

   [SELECT Id, Name FROM Account WHERE Id IN :accountIds];

        for (Account acc : accounts) {

        acc.Description = 'Updated by Queueable Apex';

        }

        update accounts;

    }

}

Interview Questions and Answers

Batch Apex

  1. Q: Why would you use Batch Apex over a normal for loop?
    A: Batch Apex is designed to handle large data volumes while respecting Salesforce governor limits by processing records in manageable chunks.

  2. Q: How do you monitor Batch Apex?
    A: You can monitor Batch Apex jobs using the Apex Jobs page in Setup or querying the AsyncApexJob table.

  3. Scenario:
    You have 10 million records in your system and need to apply a discount to customers based on certain criteria. How would you approach it?
    Answer:

    • Use Batch Apex to query the customers in manageable chunks.
    • Apply the discount logic in the execute method.
    • Commit updates to the database after processing each chunk.

@future Method

  1. Q: What are the limitations of @future methods?
    A:

    • Cannot return values.
    • Limited to 50 calls per transaction.
    • Cannot pass SObject types or collections of SObject types directly.
  2. Q: Can @future methods be chained?
    A: No, @future methods cannot be chained. For chaining, use Queueable Apex.

  3. Scenario:
    A user updates an Account, and you need to update all related Contacts asynchronously. How would you achieve this?
    Answer:

    • Use an @future method to pass the Account ID.
    • Query the related Contacts and update their fields in the @future method.

Queueable Apex

  1. Q: What is the main advantage of Queueable Apex over @future methods?
    A:

    • Supports complex data types.
    • Allows job chaining.
    • Provides job tracking via the AsyncApexJob table.
  2. Q: How do you chain Queueable jobs?
    A:

    • In the execute method of one Queueable class, enqueue another Queueable job using System.enqueueJob(new AnotherQueueableClass()).
  3. Scenario:
    You need to process records in two steps: first update records, then notify users via email. How would you achieve this?
    Answer:

    • Create two Queueable Apex classes: one for updating records and another for sending emails.
    • Chain the second job from the first using System.enqueueJob() in the execute method.

No comments:

Post a Comment