Setting Visibility Timeout in Amazon SQS - AWS SDK for Java 1.x

The AWS SDK for Java 1.x has entered maintenance mode as of July 31, 2024, and will reach end-of-support on December 31, 2025. We recommend that you migrate to the AWS SDK for Java 2.x to continue receiving new features, availability improvements, and security updates.

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

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

Code

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 on GitHub.

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

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

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 on GitHub.

More Info