Synchronous vs. Asynchronous in Apex

Synchronous vs. Asynchronous Apex – Tutorial 14

Spread the love

Synchronous and asynchronous Apex are like two ways of handling tasks in Salesforce, each with its own timing and purpose. Think of them as the difference between making immediate decisions (synchronous) and scheduling tasks for later (asynchronous).

Synchronous Apex – Immediate Actions

Synchronous Apex is like making decisions on the spot. When you trigger a synchronous process, it performs actions immediately and waits for a response before continuing. It’s like ordering fast food at a restaurant – you place an order, and you get your meal right away.

Why Synchronous Apex Is Used

Synchronous Apex is typically used for tasks that require immediate execution and a quick response. For example, when a user submits a form, you want to validate the data right away and show any errors instantly. Synchronous processes ensure that tasks happen in real-time and in a specific order.

Asynchronous Apex – Scheduled Tasks

Asynchronous Apex, on the other hand, is like scheduling tasks for later. When you trigger an asynchronous process, it queues the task for execution but doesn’t wait for the result immediately. It’s like setting a reminder on your phone to do something later.

Why Asynchronous Apex Is Used

Asynchronous Apex is used for tasks that can be done in the background or tasks that don’t need an immediate response. For example, when you need to process a large amount of data, you can use asynchronous processes to avoid slowing down the system. It’s also handy for sending emails or performing long-running operations without making users wait.

Common Use Cases

Synchronous Apex is often used for tasks like data validation, record updates, and immediate user interactions. It’s crucial for ensuring data accuracy and immediate user feedback.

Asynchronous Apex is used for tasks like data processing, long-running calculations, sending email notifications, and batch operations. It’s valuable for handling tasks that can be time-consuming or that don’t need to happen right away.

Example of Synchronous vs. Asynchronous Apex

Let’s say you have a form on your website. When a user submits the form, you want to validate the data and send a confirmation email.

  • Synchronous Apex: You validate the data and send the email immediately after the user submits the form. The user gets instant feedback.
  • Asynchronous Apex: You validate the data and schedule the email to be sent later. The user doesn’t have to wait for the email to be sent, and it won’t impact the immediate form submission.

In summary, synchronous and asynchronous Apex are two ways of handling tasks in Salesforce, each with its own timing and purpose. Synchronous processes happen immediately, while asynchronous processes can be scheduled for later execution. Understanding when to use each type of Apex is essential for building efficient and responsive Salesforce applications.

FAQs

1. What is the difference between synchronous and asynchronous Apex in Salesforce?

The difference between synchronous and asynchronous Apex in Salesforce lies in how they execute code and handle system resources. Synchronous Apex runs immediately and waits for the operation to complete before moving on to the next line of code. This means that the user must wait for the entire transaction to finish, which can impact performance if the operation takes a long time. Asynchronous Apex, on the other hand, runs in the background without waiting for the operation to complete. This allows the system to handle large data volumes and long-running processes more efficiently without blocking the user interface. Asynchronous Apex includes methods such as future methods, Batch Apex, Queueable Apex, and Scheduled Apex.

2. Why do we use asynchronous Apex in Salesforce?

We use asynchronous Apex in Salesforce to manage large data volumes and long-running operations more efficiently. Asynchronous Apex allows processes to run in the background, freeing up system resources and improving user experience by not requiring users to wait for the operations to complete. This approach is essential for tasks that exceed the governor limits of synchronous Apex, such as processing large datasets, integrating with external systems, and performing complex calculations. By leveraging asynchronous Apex, developers can ensure that their applications remain responsive and performant, even under heavy workloads.

3. Is Batch Apex synchronous or asynchronous?

Batch Apex is asynchronous. It runs in the background, allowing large volumes of data to be processed in smaller chunks without impacting the performance of other operations. Batch Apex is particularly useful for handling tasks that involve processing millions of records, data cleansing, and performing bulk updates. The asynchronous nature of Batch Apex ensures that these extensive processes do not interfere with the user interface or cause timeouts, providing a scalable solution for intensive data operations.

4. What is the limit of synchronous and asynchronous Apex?

The limits of synchronous and asynchronous Apex in Salesforce are designed to ensure system stability and performance:

  • Synchronous Apex:
    • Maximum of 100 SOQL queries per transaction.
    • Maximum of 50,000 records retrieved by SOQL queries.
    • Maximum of 150 DML operations per transaction.
    • Maximum heap size of 6 MB.
  • Asynchronous Apex:
    • Maximum of 200 SOQL queries per transaction.
    • Maximum of 50,000 records retrieved by SOQL queries.
    • Maximum of 10,000 DML operations per transaction.
    • Maximum heap size of 12 MB.

These limits help manage system resources effectively and prevent individual transactions from monopolizing shared resources in a multi-tenant environment.

5. Are Apex triggers synchronous or asynchronous?

Apex triggers are generally synchronous. They execute immediately in response to DML operations such as insert, update, delete, or undelete. Triggers run in the same transaction as the operation that caused them to fire, ensuring that all changes are processed together. However, triggers can invoke asynchronous processes like future methods or Queueable Apex if there is a need to handle operations that exceed the synchronous limits or require background processing.

6. Is Queueable Apex synchronous or asynchronous?

Queueable Apex is asynchronous. It allows developers to run Apex jobs in the background, providing more flexible and scalable processing of long-running operations. Queueable Apex is similar to future methods but offers additional benefits such as job chaining, more complex parameter passing, and better tracking of job execution. This makes it an ideal choice for handling tasks that need to be processed asynchronously without impacting the user experience.

7. What is the difference between asynchronous and synchronous?

The difference between asynchronous and synchronous processing lies in the timing and execution of tasks. Synchronous processing runs tasks sequentially, waiting for each task to complete before starting the next one. This approach ensures that operations are completed in order but can lead to delays and inefficiencies, especially for long-running tasks. Asynchronous processing, on the other hand, allows tasks to run independently in the background. This means that the system can continue executing other operations while waiting for the asynchronous task to complete. Asynchronous processing improves performance and user experience by reducing wait times and efficiently managing system resources.

8. Does Apex run synchronously?

Apex can run both synchronously and asynchronously, depending on the context and requirements. Synchronous Apex runs immediately and waits for the operation to complete before proceeding, making it suitable for real-time processing and tasks that need immediate results. Asynchronous Apex, including Batch Apex, future methods, Queueable Apex, and Scheduled Apex, runs in the background, allowing long-running or resource-intensive tasks to be processed without impacting the user interface. The choice between synchronous and asynchronous execution depends on the specific use case and the need to balance performance, resource management, and user experience.

9. How many types of asynchronous Apex are there?

There are several types of asynchronous Apex in Salesforce, each designed for different use cases:

  1. Future Methods: Used for executing long-running operations in the background, such as callouts to external services.
  2. Batch Apex: Designed for processing large volumes of data in smaller, manageable chunks, ideal for tasks like data cleansing and bulk updates.
  3. Queueable Apex: Similar to future methods but with additional features like job chaining and complex parameter passing, suitable for more flexible and trackable background processing.
  4. Scheduled Apex: Allows Apex classes to be scheduled to run at specific times, useful for recurring tasks such as nightly data updates or regular maintenance operations.

These types of asynchronous Apex provide developers with a range of tools to handle different background processing needs efficiently.

10. How to query more than 50,000 records in Salesforce?

To query more than 50,000 records in Salesforce, you can use Batch Apex. Batch Apex allows you to process large datasets by breaking them into smaller batches of up to 2000 records per batch. Here’s how you can do it:

  1. Implement Batch Apex: Create an Apex class that implements the Database.Batchable interface.
  2. Define the Start Method: In the start method, define the query to retrieve the records.apexCopy codeglobal Database.QueryLocator start(Database.BatchableContext BC) { String query = 'SELECT Id, Name FROM Account'; return Database.getQueryLocator(query); }
  3. Process Records in Execute Method: Process the records in the execute method.apexCopy codeglobal void execute(Database.BatchableContext BC, List<Account> scope) { for (Account acc : scope) { // Process each account } }
  4. Finish Method: Define any post-processing logic in the finish method.apexCopy codeglobal void finish(Database.BatchableContext BC) { // Post-processing logic }
  5. Run the Batch Job: Execute the batch job using Database.executeBatch(new YourBatchClass());.

This approach allows you to handle large volumes of data efficiently, avoiding governor limits and ensuring that your data processing tasks are completed successfully.

Seize the opportunity to enhance your career prospects with our Salesforce training in India. Enroll today and benefit from personalized mentorship from seasoned instructors. Our specialized training includes a comprehensive, project-based curriculum that imparts real-time knowledge and practical skills.

With a focus on daily notes, hands-on projects, and thorough preparation for certification and interviews, our program ensures you’re fully equipped to excel in the competitive Salesforce ecosystem. Take the next step towards achieving your career goals by enrolling in our Salesforce online course with us.


0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x
Open Chat
1
Dear Sir/Madam
How can I help you?