User guide

} catch (Exception e) {
// Do nothing because it woke up early.
}
45 } while (anyOpen);
After running this code, your Spot Instance Request will have completed or will have failed with an error
that will be output to the screen. In either case, we can proceed to the next step to clean up any active
requests and terminate any running instances.
Step 5: Cleaning Up Your Spot Requests and Instances
Lastly, we need to clean up our requests and instances. It is important to both cancel any outstanding
requests and terminate any instances. Just canceling your requests will not terminate your instances,
which means that you will continue to pay for them. If you terminate your instances, your Spot requests
may be canceled, but there are some scenarios—such as if you use persistent bids—where terminating
your instances is not sufficient to stop your request from being re-fulfilled. Therefore, it is a best practice
to both cancel any active bids and terminate any running instances.
The following code demonstrates how to cancel your requests.
1 try {
// Cancel requests.
CancelSpotInstanceRequestsRequest cancelRequest = new CancelSpotInstan
ceRequestsRequest(spotInstanceRequestIds);
ec2.cancelSpotInstanceRequests(cancelRequest);
5 } catch (AmazonServiceException e) {
// Write out any exceptions that may have occurred.
System.out.println("Error cancelling instances");
System.out.println("Caught Exception: " + e.getMessage());
System.out.println("Reponse Status Code: " + e.getStatusCode());
10 System.out.println("Error Code: " + e.getErrorCode());
System.out.println("Request ID: " + e.getRequestId());
}
To terminate any outstanding instances, you will need the instance ID associated with the request that
started them. The following code example takes our original code for monitoring the instances and adds
an ArrayList in which we store the instance ID associated with the describeInstance response.
1 // Create a variable that will track whether there are any requests
// still in the open state.
boolean anyOpen;
5 // Initialize variables.
ArrayList<String> instanceIds = new ArrayList<String>();
do {
// Create the describeRequest with all of the request ids to
10 // monitor (e.g. that we started).
DescribeSpotInstanceRequestsRequest describeRequest = new DescribeSpot
InstanceRequestsRequest();
describeRequest.setSpotInstanceRequestIds(spotInstanceRequestIds);
// Initialize the anyOpen variable to false, which assumes there
15 // are no requests open unless we find one that is still open.
anyOpen = false;
Version v1.0.0
42
AWS SDK for Java Developer Guide
Tutorial: Amazon EC2 Spot Instances