AI-generated Key Takeaways
-
Several API calls initiate long-running operations, tracked by jobs that execute over time, making blocking RPCs undesirable.
-
The
OperationFuture
class facilitates interaction with long-running operations, but requires the service client to remain active during its usage. -
Directly using
OperationFuture
within a method without ensuring the service client's lifespan can lead to issues. -
It's recommended to utilize
OperationFuture
within the scope of the service client, as demonstrated in the "Recommended" code example, to prevent premature client destruction.
Several calls to the API return long-running operations. These track the status of a job which executes over an extended period of time, such that having a blocking RPC is not desirable.
OperationFuture class
The most obvious way to interact with LROs is with the
OperationFuture
class. If you use this, make sure that the service client is not destroyed.
Not recommended:
private void doSomething() {
OperationFuture<Empty, Empty> future = startLongRunningOperation(jobName);
future.get();
}
private OperationFuture<Empty, Empty> startLongRunningOperation(String jobToStart)
throws UnsupportedEncodingException {
try (OfflineUserDataJobServiceClient offlineUserDataJobServiceClient =
googleAdsClient.getLatestVersion().createOfflineUserDataJobServiceClient()) {
// Issues an asynchronous request to run the offline user data job for executing
// all added operations.
return offlineUserDataJobServiceClient.runOfflineUserDataJobAsync(jobToStart);
}
}
Recommended:
private void doSomethingElse() {
try (OfflineUserDataJobServiceClient offlineUserDataJobServiceClient =
googleAdsClient.getLatestVersion().createOfflineUserDataJobServiceClient()) {
OperationFuture<Empty, Empty> future = startLongRunningOperation(offlineUserDataJobServiceClient, jobName);
future.get();
}
}
private OperationFuture<Empty, Empty> startLongRunningOperation(String jobToStart)
throws UnsupportedEncodingException {
offlineUserDataJobServiceClient.runOfflineUserDataJobAsync(jobToStart);
}
Notice how the OperationFuture
class is only used while the
OfflineUserDataJobServiceClient
is in scope.