Menu
AWS SDK for Java
Developer Guide

Setting Visibility Timeout in Amazon SQS

When a message is received in Amazon SQS, it remains on the queue until it's deleted in order to ensure receipt. A message that was received, but not deleted, will be available in subsequent requests after a given visibility timeout to help prevent the message from being received more than once before it can be processed and deleted.

Note

When using standard queues, visibility timeout isn't a guarantee against receiving a message twice. If you are using a standard queue, be sure that your code can handle the case where the same message has been delivered more than once.

Setting the Message Visibility Timeout for a Single Message

When you have received a message, you can modify its visibility timeout by passing its receipt handle in a ChangeMessageVisibilityRequest that you pass to the AmazonSQS class' changeMessageVisibility method.

Imports

Copy
import com.amazonaws.services.sqs.AmazonSQS; import com.amazonaws.services.sqs.AmazonSQSClientBuilder;

Code

Copy
AmazonSQS sqs = AmazonSQSClientBuilder.defaultClient(); // Get the receipt handle for the first message in the queue. String receipt = sqs.receiveMessage(queue_url) .getMessages() .get(0) .getReceiptHandle(); sqs.changeMessageVisibility(queue_url, receipt, timeout);

See the complete example.

Setting the Message Visibility Timeout for Multiple Messages at Once

To set the message visibility timeout for multiple messages at once, create a list of ChangeMessageVisibilityBatchRequestEntry objects, each containing a unique ID string and a receipt handle. Then, pass the list to the Amazon SQS client class' changeMessageVisibilityBatch method.

Imports

Copy
import com.amazonaws.services.sqs.AmazonSQS; import com.amazonaws.services.sqs.AmazonSQSClientBuilder; import com.amazonaws.services.sqs.model.ChangeMessageVisibilityBatchRequestEntry; import java.util.ArrayList; import java.util.List;

Code

Copy
AmazonSQS sqs = AmazonSQSClientBuilder.defaultClient(); List<ChangeMessageVisibilityBatchRequestEntry> entries = new ArrayList<ChangeMessageVisibilityBatchRequestEntry>(); entries.add(new ChangeMessageVisibilityBatchRequestEntry( "unique_id_msg1", sqs.receiveMessage(queue_url) .getMessages() .get(0) .getReceiptHandle()) .withVisibilityTimeout(timeout)); entries.add(new ChangeMessageVisibilityBatchRequestEntry( "unique_id_msg2", sqs.receiveMessage(queue_url) .getMessages() .get(0) .getReceiptHandle()) .withVisibilityTimeout(timeout + 200)); sqs.changeMessageVisibilityBatch(queue_url, entries);

See the complete example.

More Info