Synchronous and asynchronous modes

Updated at:
Copy as MD

This topic describes the architectural models of the Alibaba Cloud Java SDK. You can choose the model that best suits your application to design efficient and reliable Java programs.

The Alibaba Cloud Java SDK provides two programming models: synchronous and asynchronous. They differ mainly in how they execute requests, handle responses, and affect the calling thread.

Synchronous vs. asynchronous modes

Mode

Pros

Cons

Synchronous

  • Simple and intuitive: The execution order of synchronous operations matches the code order, making the logic easy to understand and debug.

  • Straightforward error handling: Handling exceptions and errors is typically more direct because the code executes sequentially and provides immediate feedback when an error occurs.

  • Direct flow control: Because the program executes sequentially, flow control is more direct, which makes it easier to ensure data consistency and integrity.

  • Blocking: During long-running operations like I/O or network requests, the calling thread is blocked until the operation completes, which reduces efficiency.

  • Performance bottlenecks: In high-concurrency scenarios with many long-running operations, synchronous execution can cause low resource utilization, leading to response delays or system freezes.

  • Poor user experience: In GUI applications or web services, synchronous operations can cause the user interface to become unresponsive or pages to load slowly.

Asynchronous

  • Non-blocking: Asynchronous execution allows the program to continue with other tasks while waiting for long-running operations, such as I/O operations, to complete. This improves application responsiveness and efficiency.

  • Improved concurrency: Asynchronous processing makes better use of system resources to handle more concurrent requests, making it ideal for high-performance and high-concurrency scenarios.

  • Enhanced user experience: In UI applications, asynchronous processing keeps the interface responsive, improving the user experience.

  • Increased complexity: The asynchronous programming model is more complex, requiring mechanisms like callbacks, Promises, or async/await, which makes code harder to write and maintain.

  • Difficult debugging: The non-linear flow of asynchronous execution makes debugging and error tracing more challenging.

  • Resource management: Asynchronous operations can involve more resource allocation and management, such as a thread pool or an event loop. Improper management can cause resource leaks or performance degradation.

Synchronous mode

In synchronous mode, after you make a request, the calling thread waits for the operation to complete and return a result. The thread is blocked and cannot perform other tasks during this time. This mode is suitable for scenarios that are sensitive to latency but do not require high throughput, as it ensures sequential execution and immediate results. You can use the Alibaba Cloud Java SDK to implement this mode. To get the SDK:

  1. Go to the Alibaba Cloud official website.

  2. In the top menu, select Products, and then select a product such as ECS.

  3. In the All Languages section, select Java.

  4. Select your preferred Installation Method and copy the code to your project.

    On the ECS SDK page in the OpenAPI Portal, select Java as the language and V2.0 as the SDK version. The minimum requirement is Java 8. In the Installation Method area, select the Apache Maven tab. The corresponding Maven dependency has a groupId of com.aliyun, an artifactId of ecs20140526, and a version of 5.1.8.

  5. Install the SDK in your project.

Example code

import com.aliyun.ecs20140526.models.DescribeRegionsRequest;
import com.aliyun.ecs20140526.models.DescribeRegionsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
public class Sample {
    public static void main(String[] args) throws Exception {
        Config config = new com.aliyun.teaopenapi.models.Config();
        // Obtain the AccessKey ID of the RAM user from an environment variable.
        config.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"));
        // Obtain the AccessKey Secret of the RAM user from an environment variable.
        config.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
        // Region ID
        config.setRegionId("cn-hangzhou");
        com.aliyun.ecs20140526.Client client = new com.aliyun.ecs20140526.Client(config);
        // Configure runtime retry settings. These settings apply only to requests made with this RuntimeOptions instance.
        RuntimeOptions runtimeOptions = new RuntimeOptions();
        DescribeRegionsRequest describeRegionsRequest = new DescribeRegionsRequest();
        // Make a synchronous call.
        DescribeRegionsResponse describeRegionsResponse = client.describeRegionsWithOptions(describeRegionsRequest, runtimeOptions);
        System.out.println(describeRegionsResponse.getBody());
    }
}

Asynchronous mode

In asynchronous mode, after sending a request, the calling thread can continue with other tasks without waiting for the operation to complete. The operation typically returns its result through a callback, event, or Future object. This mode is suitable for scenarios that require high throughput and system responsiveness. It is especially effective for handling a large number of concurrent requests, as it prevents threads from being blocked for long periods and improves overall processing efficiency. You can use the Java (async) SDK to implement this mode. To get the SDK:

  1. Go to the Alibaba Cloud official website.

  2. In the top menu, select Products, and then select a product such as ECS.

  3. In the All Languages section, select Java (async).

  4. Select your preferred Installation Method and copy the code to your project.

    In the OpenAPI Portal, select the product ECS, set the SDK version to V2.0 (Recommended), and select Java (async) as the language. The minimum requirement is Java 8. For Apache Maven, add a dependency to your project's pom.xml file with a groupId of com.aliyun, an artifactId of alibabacloud-ecs20140526, and a version of 5.0.12. You can find other installation methods, such as Gradle Groovy DSL, Gradle Kotlin DSL, and Scala SBT, by switching tabs on the page.

  5. Install the SDK in your project.

Example code

import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.ecs20140526.AsyncClient;
import com.aliyun.sdk.service.ecs20140526.models.DescribeRegionsRequest;
import com.aliyun.sdk.service.ecs20140526.models.DescribeRegionsResponse;
import com.google.gson.Gson;
import darabonba.core.client.ClientOverrideConfiguration;
import java.util.concurrent.CompletableFuture;
public class DescribeRegions {
    public static void main(String[] args) throws Exception {
        // Use a static credential provider to obtain access credentials from environment variables.
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                // Obtain the AccessKey ID and AccessKey Secret of the RAM user from environment variables.
                .accessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
                .accessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"))
                .build());
        // Build the asynchronous client and specify the region and credential provider.
        AsyncClient client = AsyncClient.builder()
                .region("cn-hangzhou") // Region ID
                .credentialsProvider(provider)
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                // For the endpoint, see https://api.aliyun.com/product/Ecs
                                .setEndpointOverride("ecs.cn-chengdu.aliyuncs.com")
                )
                .build();
        // Create a request object to query all regions.
        DescribeRegionsRequest describeRegionsRequest = DescribeRegionsRequest.builder()
                .build();
        // Make an asynchronous request and get the Future object for the response.
        CompletableFuture<DescribeRegionsResponse> response = client.describeRegions(describeRegionsRequest);
        // Get the result (blocks the calling thread until the asynchronous call completes).
        DescribeRegionsResponse resp = response.get();
        // Print the result.
        System.out.println(new Gson().toJson(resp));
        // Get the result (does not block the calling thread, allowing it to continue with other tasks and improving application concurrency and responsiveness).
        /*response.thenAccept(resp -> {
            System.out.println(new Gson().toJson(resp));
        }).exceptionally(throwable -> { // Handling exceptions
            System.out.println(throwable.getMessage());
            return null;
        });*/
        // Close the client to release resources.
        client.close();
    }
}