User guide

10 // active state.
for (SpotInstanceRequest requestResponse : requestResponses) {
System.out.println("Created Spot Request: "+requestResponse.getSpotIn
stanceRequestId());
spotInstanceRequestIds.add(requestResponse.getSpotInstanceRequestId());
}
To monitor your request ID, call the describeSpotInstanceRequests method to determine the state
of the request. Then loop until the request is not in the "open" state. Note that we monitor for a state of
not "open", rather a state of, say, "active", because the request can go straight to "closed" if there is a
problem with your request arguments.The following code example provides the details of how to
accomplish this task.
1 // Create a variable that will track whether there are any
// requests still in the open state.
boolean anyOpen;
5 do {
// Create the describeRequest object with all of the request ids
// to monitor (e.g. that we started).
DescribeSpotInstanceRequestsRequest describeRequest = new DescribeSpot
InstanceRequestsRequest();
describeRequest.setSpotInstanceRequestIds(spotInstanceRequestIds);
10
// Initialize the anyOpen variable to false - which assumes there
// are no requests open unless we find one that is still open.
anyOpen=false;
15 try {
// Retrieve all of the requests we want to monitor.
DescribeSpotInstanceRequestsResult describeResult = ec2.describeS
potInstanceRequests(describeRequest);
List<SpotInstanceRequest> describeResponses = describeResult.get
SpotInstanceRequests();
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);
Version v1.0.0
41
AWS SDK for Java Developer Guide
Tutorial: Amazon EC2 Spot Instances