Synchronous and asynchronous modes
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 |
|
|
|
Asynchronous |
|
|
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:
-
Go to the Alibaba Cloud official website.
-
In the top menu, select Products, and then select a product such as ECS.
-
In the All Languages section, select Java.
-
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
groupIdofcom.aliyun, anartifactIdofecs20140526, and aversionof5.1.8. -
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:
-
Go to the Alibaba Cloud official website.
-
In the top menu, select Products, and then select a product such as ECS.
-
In the All Languages section, select Java (async).
-
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.xmlfile with agroupIdofcom.aliyun, anartifactIdofalibabacloud-ecs20140526, and aversionof5.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. -
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();
}
}