User guide

20 // Look through each request and determine if they are all in
// the active state.
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
25 // almost immediately to closed or cancelled so we compare
// against open instead of active.
if (describeResponse.getState().equals("open")) {
anyOpen = true;
break;
30 }
}
} catch (AmazonServiceException e) {
// If we have an exception, ensure we don't break out of
// the loop. This prevents the scenario where there was
35 // blip on the wire.
anyOpen = true;
}
try {
40 // Sleep for 60 seconds.
Thread.sleep(60*1000);
} 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());
}
Version v1.0.0
43
AWS SDK for Java Developer Guide
Tutorial: Amazon EC2 Spot Instances