1. What are the governor limit in Asynchronous Apex?
2. Explain methods used in batch Apex?
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 for post-processing operations such as sending an email. When this process is called all batches are already executed.
3. How to Invoke a Batch Class?
Database.executeBatch(new BatchApexExample(),100);
4. How to Monitor Batch Apex?
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?
At maximum, only 5 Batch jobs can be chained to one another. global database.query locator 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?
It is a Database. Batchable interface
7. Why use Batch Apex in Salesforce instead of the normal Apex? 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?
Salesforce by default allows 5 active batches running at a time and other batches will be in queue for running
9. Why to use the Batch class as we already have a data loader to process the bulk data?
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 that can’t be driven by excel sheets in those cases, we have to go with batch classes.
Examples: Do some relationship queries 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.
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 ?
2000
12.What is the minimum batch size we can set up is?
1
13.What is the default size of batch if we haven’t configured at the time of execution?
200
14. What is Apex Flex Queue?
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?
100
16. Why call only from the finish method why not from execute?
This is because the execute method will get invoked multiple times based on the volume of the records and batch size. So,if you’re calling it from the execute method then the chaining class will get called multiple times which is not a suggested way of doing it.
17.What is the difference between queryLocator object and Iterable used in batch apex?
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?
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 a Database?
If you specify a Database. Stateful in the class definition, you can maintain state across all transactions. When using a 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 them in the notification email.
20.When to use batch apex instead of Queueable Apex?
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?
To use HTTP Callouts in batch class we need to use Database. allow callouts in the interface.
22. If a batch is having 200 records and 1 record fails what will happen?
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?
Yes, we can call from the finish method.
24. Can we call batch apex into another batch in execute method?
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?
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?
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?
No,we can’t call.
28.Can I call Queueable from a batch?
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?
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? 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?
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?
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 one to the back.
Boolean isSuccess = System.FlexQueue.moveBeforeJob(jobToMoveId, jobInQueueId);
33. Explain status of jobs in Apex Flex Queue?
Holding: The job has been submitted and is held in the Apex flex queue until system resources become available to queue the job for processing.
Queued: The 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: The 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?
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 Limit Exception 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? 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 a Database?QueryLocator? 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.
37. Can you write a batch class blueprint?
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 } }
38. 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 the 395th record, an error occurred, What will happen in that case?
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, and update than the whole batch will be rollbacked. So records 201 to 400 will not be processed.
39. How can you stop a Batch job?
The Database.executeBatch and System.scheduleBatch method returns an ID that can be used in System.abortJob method.
40. Call we call future method in batch class?
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.
41.How to use Aggregate queries in Batch Apex
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’
42.What is the difference between database.batchable & database.batchablecontext bc?
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.
43. What if you change the name of Execute method to Execute1 in the batch class? Will the batch job still run?
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 the class must implement the execute method.
44. Is there a way in which I can call a future method from a batch Job?
Calling a future method is not allowed in the Execute method, but a web service can be called. A web service can also be called 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.
45.What is batchable context? why we need it?
1. Database. Batchable is an interface.
2. database.batchableContext is a context variable which stores 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.
46. Can I write methods other than start, execute, and finish?
No we cannot write other method. Whatever method is there is Database. batchable interface only that we can call.
47.Why batch class is global?
global makes a class usable by code outside of a managed package.
48. insert vs database?
If we use the DML statement (insert), then in bulk operation if an 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) are used, then if an error occurs the remaining records will be inserted/updated means partial DML operation will be done.
49.database.insert vs Stateful?
Database. insert – It shows failure for records where the complete batch is failed and wont picks the records where some records are passed for a particular batch and therefore we need to use a database. stateful
50.Is finish asynchronous?
The finish method is sync because it does not go in the queue. The 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.