User guide

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.
}
} while (anyOpen);
Using the instance IDs, stored in the ArrayList, terminate any running instances using the following
code snippet.
1 try {
// Terminate instances.
TerminateInstancesRequest terminateRequest = new TerminateInstances
Request(instanceIds);
ec2.terminateInstances(terminateRequest);
5 } catch (AmazonServiceException e) {
// Write out any exceptions that may have occurred.
System.out.println("Error terminating 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());
}
Version v1.0.0
43
AWS SDK for Java Developer Guide
Tutorial: Amazon EC2 Spot Instances