User guide

RequestSpotInstancesRequest requestRequest = new RequestSpotInstances
Request();
// Request 1 x t1.micro instance with a bid price of $0.03.
requestRequest.setSpotPrice("0.03");
20 requestRequest.setInstanceCount(Integer.valueOf(1));
// Setup the specifications of the launch. This includes the
// instance type (e.g. t1.micro) and the latest Amazon Linux
// AMI id available. Note, you should always use the latest
25 // Amazon Linux AMI id or another of your choosing.
LaunchSpecification launchSpecification = new LaunchSpecification();
launchSpecification.setImageId("ami-8c1fece5");
launchSpecification.setInstanceType("t1.micro");
30 // Add the security group to the request.
ArrayList<String> securityGroups = new ArrayList<String>();
securityGroups.add("GettingStartedGroup");
launchSpecification.setSecurityGroups(securityGroups);
35 // Add the launch specifications to the request.
requestRequest.setLaunchSpecification(launchSpecification);
// Call the RequestSpotInstance API.
RequestSpotInstancesResult requestResult = ec2.requestSpotInstances(re
questRequest);
Running this code will launch a new Spot Instance Request.There are other options you can use to
configure your Spot Requests.To learn more, please visit the Java Developers: Advanced Spot Features
Tutorials or the RequestSpotInstances API in the SDK for Java.
Note
You will be charged for any Spot Instances that are actually launched, so make sure that you
cancel any requests and terminate any instances you launch to reduce any associated fees.
Step 4: Determining the State of Your Spot Request
Next, we want to create code to wait until the Spot request reaches the "active" state before proceeding
to the last step. To determine the state of our Spot request, we poll the describeSpotInstanceRequests
method for the state of the Spot request ID we want to monitor.
The request ID created in Step 2 is embedded in the response to our requestSpotInstances request.
The following example code shows how to gather request IDs from the requestSpotInstances response
and use them to populate an ArrayList.
1 // Call the RequestSpotInstance API.
RequestSpotInstancesResult requestResult = ec2.requestSpotInstances(re
questRequest);
List<SpotInstanceRequest> requestResponses = requestResult.getSpotInstance
Requests();
5 // Setup an arraylist to collect all of the request ids we want to
// watch hit the running state.
ArrayList<String> spotInstanceRequestIds = new ArrayList<String>();
// Add all of the request ids to the hashset, so we can determine when they
hit the
Version v1.0.0
40
AWS SDK for Java Developer Guide
Tutorial: Amazon EC2 Spot Instances