User guide
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;
try {
// Retrieve all of the requests we want to monitor.
20 DescribeSpotInstanceRequestsResult describeResult = ec2.describeS
potInstanceRequests(describeRequest);
List<SpotInstanceRequest> describeResponses = describeResult.get
SpotInstanceRequests();
// Look through each request and determine if they are all
// in the active state.
25 for (SpotInstanceRequest describeResponse : describeResponses) {
// If the state is open, it hasn't changed since we
// attempted to request it. There is the potential for
// it to transition almost immediately to closed or
// cancelled so we compare against open instead of active.
30 if (describeResponse.getState().equals("open")) {
anyOpen = true;
break;
}
35 // Add the instance id to the list we will
// eventually terminate.
instanceIds.add(describeResponse.getInstanceId());
}
} catch (AmazonServiceException e) {
40 // If we have an exception, ensure we don't break out
// of the loop. This prevents the scenario where there
// was blip on the wire.
anyOpen = true;
}
45
try {
// Sleep for 60 seconds.
Thread.sleep(60*1000);
} catch (Exception e) {
50 // Do nothing because it woke up early.
Version v1.0.0
44
AWS SDK for Java Developer Guide
Tutorial: Amazon EC2 Spot Instances