AWS Developer Tools Blog

Snippet: Creating Amazon DynamoDB Tables

In many applications, it’s important to make sure your code handles creating any resources that it needs in order to run. Otherwise, you’ll have to manually create those resources whenever you want to run your application with a new AWS account.

For example, if you have an application that needs to store data in an Amazon DynamoDB table, then you’ll probably want your application to check if that table exists at startup, create it if necessary, and only let your application logic start running once that table is ready to use.

The following code demonstrates how to create a simple Amazon DynamoDB table using the SDK:

AmazonDynamoDB dynamo = new AmazonDynamoDBClient(myCredentials);

CreateTableRequest request = new CreateTableRequest().withTableName("customers");

request.withKeySchema(new KeySchemaElement()
        .withAttributeName("customerId")
        .withKeyType(KeyType.HASH));

request.withAttributeDefinitions(new AttributeDefinition()
        .withAttributeName("customerId")
        .withAttributeType(ScalarAttributeType.S));

request.setProvisionedThroughput(new ProvisionedThroughput()
        .withReadCapacityUnits(5)
        .withWriteCapacityUnits(2));

dynamo.createTable(request);

This code creates a simple table called customers, specifies low values for provisioned throughput, and declares the hash key (think: primary key) to be an attribute named id with type String.

Once you’ve created your table, you’ll want to make sure it’s ready for use before you let your application logic start executing; otherwise, you’ll get errors from Amazon DynamoDB when you try to use it.

The following function, taken from some of our SDK test code for DynamoDB, demonstrates how to poll the status of a table and detect when the table is ready for use.

protected static void waitForTableToBecomeAvailable(String tableName) throws InterruptedException {
    System.out.println("Waiting for " + tableName + " to become ACTIVE...");

    long startTime = System.currentTimeMillis();
    long endTime = startTime + (10 * 60 * 1000);
    while ( System.currentTimeMillis() < endTime ) {
        Thread.sleep(1000 * 20);
        try {
            DescribeTableRequest request = new DescribeTableRequest()
                 .withTableName(tableName);
            TableDescription table = dynamo.describeTable(request).getTable();
            if ( table == null ) continue;

            String tableStatus = table.getTableStatus();
            System.out.println("  - current state: " + tableStatus);
            if ( tableStatus.equals(TableStatus.ACTIVE.toString()) )
                return;
        } catch ( AmazonServiceException ase ) {
            if (!ase.getErrorCode().equalsIgnoreCase("ResourceNotFoundException"))
                throw ase;
        }
    }

    throw new RuntimeException("Table " + tableName + " never went active");
}

You can use this same logic to wait for your new table to become active. Then it’s ready for your data!

How are you managing your AWS resources? Do your applications automatically create all the AWS resources they need? Are you using AWS CloudFormation to handle resource creation?