“Cracking the Code: Key Asynchronous Apex Questions for Salesforce Interviews” is your go-to guide for preparing for Salesforce interviews, focusing specifically on the Asynchronous Apex framework. This blog dives deep into the most commonly asked questions related to Asynchronous Apex, covering key concepts like future methods, batch processing, Queueable Apex, and scheduled jobs. Whether you’re a seasoned Salesforce developer or just getting started, this article will equip you with the knowledge and confidence to answer challenging interview questions and demonstrate your expertise in handling complex asynchronous processes within Salesforce.
1.What are the governor limit in Asynchronous Apex?
Ans.
2. Explain methods used in batch Apex?
Ans.
Start: This method is called at the starting of a batch job to collect the data
on which the batch job will be operating. It breaks the data or record into
batches
Execute: This method executes after the Start method, and it does the
actual processing for each batch, separately.
global void execute(Database.BatchableContext BC, list<sobject<) {}
Finish: This method will be called at last. Since this method is called in the
end, it is responsible to perform post-processing operations such as
sending an email. When this process is called all batches are already
executed.
global void finish(Database.BatchableContext BC) {}
3. How to Invoke a Batch Class?
Ans. Database.executeBatch(new BatchApexExample(),100);
4. How to Monitoring Batch Apex?
Ans. To monitor or stop the execution of the batch Apex job, from Setup, enter
Apex Jobs in the Quick Find box, then select Apex Jobs.
5. Explain Chaining in Batch Apex?
Ans. At maximum, only 5 Batch jobs can be chained to one another.
global database.querylocator start(Database.BatchableContext BC)
{
//start method logic here
}
global void execute(Database.BatchableContext BC, List<sObject> scope)
{
//start method logic here
}
global void finish(Database.BatchableContext BC)
{
//Batch Chaining Step Starts here
AccountBatch accBatch = new AccountBatch ();
Id batchProcessId = Database.executeBatch(accBatch);
//finish method logic here
}
6. What interface will you use for batch apex?
Ans. It is Database.Batchable interface
7.Why use Batch Apex in Salesforce instead of the normal Apex?
Ans. There are various reasons why Batch Apex is better than normal Apex.
• SOQL queries: Normal Apex uses 100 records per cycle to execute
SOQL queries. Whereas, Batch Apex does the same in 200 records
per cycle.
• Retrieval of SOQL queries: Normal Apex can retrieve 50,000 SOQL
queries but, in Batch Apex, 50,000,000 SOQL queries can be
retrieved.
• Heap size: Normal Apex has a heap size of 6 MB; whereas, Batch
Apex has a heap size of 12 MB.
8. How many active batches(running parallel) can be allowed at a
time?
Ans. Salesforce by default allows 5 active batches running at a time and other
batches will be in queue for running
9.Why to use Batch class as we already having data loader to process
the bulk data.
Ans. Agree with this point if and only if the data needs to be updated is static or
predefined or which can be done through excel.
We will choose batch class if we have to perform some custom calculations
at run time or if you want to run some complex logic which can’t be driven
by excel sheets in those cases, we have to go with batch classes.
Examples:
Do some relationship quires to update the data.
Make a call out to get some information related to each record.
10.How many times the execute method will be executed to process
the 1234 records.
Ans. It depends on your batch size what you have configured at the time of
calling the batch class from schedule class.
Execution method count = Total No Of Records/Batch Size (Any decimal
ceil it to upper value)
If you haven’t set any batch size then – 1234/200 = 6.17 = 7 times execute
method will be called
11.What is the maximum size of a batch that we can set up ?
Ans. 2000
12.What is the minimum batch size we can set up is?
Ans. 1
13.What is the default size of batch if we haven’t configured at the
time of execution?
Ans. 200
14. What is Apex Flex Queue?
Ans. At a time salesforce allows 5 batches to be running or to be in queued
state.So,if you have consumed all these 5 limits and if system has received
one or more batch execution request all these waiting batch will be stored
in this Apex Flex Queue.
15. What is the maximum number of batch classes allowed in Apex
Flex Queue for execution?
Ans. 100
16. Why to call only from the finish method why not from execute?
Ans. It is because the execute method will gets invoked multiple times based on
the volume of the records and batch size.So,if you’re calling it from execute
method then the chaining class will get called multiple times which is not an
suggested way of doing.
17.What is the difference between queryLocator object and Iterable
used in batch apex?
Ans. QueryLocator object, the governor limit for the total number of records
retrieved by SOQL queries is bypassed and you can query up to 50 million
records. However, with an Iterable, the governor limit for the total number of
records retrieved by SOQL queries is still enforced.
18. What is the state of batch apex?
Ans. Batch Apex is typically stateless. Each execution of a batch Apex job is
considered a discrete transaction. For example, a batch Apex job that
contains 1,000 records and uses the default batch size is considered five
transactions of 200 records each.
19.What is the use of Database.Stateful?
Ans. If you specify Database.Stateful in the class definition, you can maintain
state across all transactions. When using Database.Stateful, only instance
member variables retain their values between transactions. Maintaining
state is useful for counting or summarizing records as they’re processed.
For example, we’ll be updating contact records in our batch job and want to
keep track of the total records affected so we can include it in the
notification email.
20.When to use batch apex instead of Queueable Apex?
Ans. Only you should use Batch Apex if you have more than one batch of
records. If you don’t have enough records to run more than one batch, you
should use Queueable Apex.
21.How to use HTTP Callouts in batch class?
Ans. To use HTTP Callouts in batch class we need to use
Database.allowcallouts in interface.
22. If a batch is having 200 records and 1 record fails what will
happen?
Ans. If any record fails all 200 record will fail but next batch will get executed
23. Can we call the batch into another batch apex?
Ans. Yes, we can call from the finish method.
24. Can we call batch apex into another batch in execute method?
Ans. Only in batch class finish method, We can call another batch class. If you
will call another batch class from batch class execute and start method,
then Salesforce will throw below runtime error.
System.AsyncException: Database.executeBatch cannot be called from a
batch start, batch execute, or future method.
25.Can we call the batch apex from triggers in salesforce?
Ans. Yes, it is possible. We can call a batch apex from trigger but we should
always keep in mind that we should not call batch apex from trigger each
time as this will exceeds the governor limit this is because of the reason
that we can only have 5 apex jobs queued or executing at a time.
26.How many times start,execute,finish methods will execute in batch
apex?
Ans. Start method,finish method one time, execute method it depends on
requirement. Based on the batch size and data retrieved in Start method.
27.Can we call the future method in batch class?
Ans. No,we can’t call.
28.Can I call Queueable from a batch?
Ans. Yes, But you’re limited to just one System.enqueueJob call per execute in
the Database.Batchable class. Salesforce has imposed this limitation to
prevent explosive execution.
29.How to test batch apex?
Ans. Code is run between test.startTest and test.stopTest. Any asynchronous
code included within Test.startTest and Test.stopTest is executed
synchronously after Test.stopTest.
30.How many records we can insert while testing batch apex?
Ans. We have to make sure that the number of records inserted is less than or
equal to the batch size of 200 because test methods can execute only one
batch. We must also ensure that the Iterable returned by the start method
matches the batch size.
31. What is apex Flex Queue?
Ans. The Apex Flex queue enables you to submit up to 100 batch jobs for
execution. Any jobs that are submitted for execution are in holding status
and are placed in the Apex Flex queue. Up to 100 batch jobs can be in the
holding status.
32. Can you change order of job in Apex Flex Queue?
Ans. Jobs are processed first-in first-out—in the order in which they’re
submitted. You can look at the current queue order and shuffle the queue,
so that you could move an important job to the front, or less important ones
to the back.
Boolean isSuccess = System.FlexQueue.moveBeforeJob(jobToMoveId,
jobInQueueId);
33. Explain status of jobs in Apex Flex Queue?
Ans.
Holding : Job has been submitted and is held in the Apex flex queue until
system resources become available to queue the job for processing.
Queued : Job is awaiting execution.
Preparing : The start method of the job has been invoked. This status can
last a few minutes depending on the size of the batch of records.
Processing: Job is being processed.
Aborted : Job aborted by a user.
Completed : Job completed with or without failures.
Failed : Job experienced a system failure.
34. Let’s say, I have 150 Batch jobs to execute, Will I be able to queue
them in one go?
Ans. Once you run Database.executeBatch, the Batch jobs will be placed in the
Apex flex queue and its status becomes Holding. The Apex flex queue has
the maximum number of 100 jobs, Database.executeBatch throws a
LimitException and doesn’t add the job to the queue. So atmost 100 jobs
can be added in one go.
Also, if Apex flex queue is not enabled, the Job status becomes Queued,
Since the concurrent limit of the queued or active batch is 5, so atmost 5
batch jobs can be added in one go.
35. Can I Use FOR UPDATE in SOQL using Database.QueryLocator?
Ans. No, We can’t. It will throw an exception stating that “Locking is implied for
each batch execution and therefore FOR UPDATE should not be specified”
List<Account> accounts = [SELECT Id, Name FROM Account WHERE
Name = ‘SpecificAccountName’ FOR UPDATE];
36.Can I query related records using Database.QueryLocator?
Ans. Yes, You can do subquery for related records, but with a relationship
subquery, the batch job processing becomes slower. A better strategy is to
perform the subquery separately, from within the execute method, which
allows the batch job to run faster.
36. Can you write a batch class blueprint?
Ans.
global class batchExample implements Database.Batchable<sObject> {
global (Database.QueryLocator | Iterable<sObject>)
start(Database.BatchableContext bc) {
// collect the batches of records or objects to be passed to execute
}
global void execute(Database.BatchableContext bc, List<sObject>
records){
// process each batch of records
}
global void finish(Database.BatchableContext bc){
// execute any post-processing operations
}
}
37.Let’s say, we have run an apex batch to process 1000 records, and
It is running with batch size 200. Now, while doing DML on 395th
record, an error occurred, What will happen in that case?
Ans. In batches, If the first transaction succeeds but the second fails, the
database updates made in the first transaction are not rolled back.
Since the batch size is 200, so the first batch will be processed completely,
and all data will be committed to DB. In seconds batch, if we are
committing records using normal DML statements like insert, update than
the whole batch will be rollbacked. So records 201 to 400 will not be
processed.
38. How can you stop a Batch job?
Ans. The Database.executeBatch and System.scheduleBatch method returns an
ID that can be used in System.abortJob method.
39. Call we call future method in batch class?
Ans. Methods declared as future can’t be called from Batch Apex class.
Batch class and future method are designed for a different kind of task.
Batch Apex is like a heavy-duty used for big tasks (processing lots of data),
while future methods are more like a screwdriver, good for smaller, quick
fixes (simple, one-time operations- a method). They work differently, so
they can’t always be used together.
40.How to use Aggregate queries in Batch Apex
Ans. Aggregate queries don’t work in Batch Apex because aggregate queries
doesn’t support queryMore(). They run into the error ‘Aggregate query
does not support queryMore(), use LIMIT to restrict the results to a
single batch’
41.What is the difference between database.batchable &
database.batchablecontext bc?
Ans. Database.Batchable (Interface):
• Think of this as a blueprint that your Apex class needs to follow.
• When you implement Database.Batchable, you’re telling Salesforce
that your class is ready to be used for batch processing.
• It defines the methods your class must have, like start(), execute(),
and finish().
Database.BatchableContext (Context Variable):
• It stores runtime information about the batch job, like the job ID and
other details.
• You can use this to access and work with information related to the
current batch job.
42.What if you change the name of Execute method to Execute1 in the
batch class? Will the batch job still run?
Ans. Go ahead and change Execute to Excute1 and try saving the class.
Output
Class batchUpdateAccountsContacts must implement the method: void
Database.Batchable<SObject>.execute(Database.BatchableContext,
List<SObject>)
Finding
It won let you save the batch class as it says class must implement execute
method.
43.Is there a way in which I can call a future method from a batch
Job?
Ans. Calling a future method is not allowed in the Execute method, but a web
service can be called. A web service can also call an @future method. So,
we can define a web service having a future method invocation and call the
web service from the execute method of Batch Job.
44.What is batchable context? why we need it?
Ans.
1. database.batchable is an interface.
2. database.batchableContext is a context variable which store the runtime
information eg jobId
It gives the context of the batch class. Represents the parameter type of a
batch job method and contains the batch job ID.
45.Can I write method other than start, execute, finish?
Ans. No we cannot write other method. Whatever method is there is
Database.batchable interface only that we can call.
46.Why batch class is global?
Ans. global makes a class usable by code outside of a managed package.
47.insert vs database.insert?
Ans. If we use the DML statement (insert), then in bulk operation if error occurs,
the execution will stop and Apex code throws an error which can be
handled in try catch block.
If DML database methods (Database.insert) used, then if error occurs the
remaining records will be inserted / updated means partial DML operation
will be done.
48.database.insert vs Stateful?
Ans.
Database.insert – It show failure for records where complete batch is failed
and wont pick the records where some records are passed for a particular
batch and therefore we need to use database.stateful
49.Is finish asynchronous?
Ans. Finish method is sync because it does not go in queue. Only execute
method is async.
Execute method: The execute method is asynchronous. It processes
records in batches and may make use of the Salesforce job queue.
Records are processed in the background.
Finish method: The finish method, on the other hand, is synchronous. It
doesn’t go into a queue, and it runs immediately after the execute method
has completed processing all records.
50.What we do to do callout from batch?
Ans.
1. Use Database.allowcallout interface on class level
2. Do callout from execute method.