SimpleQueueServiceMultiThread.java Source code

Java tutorial

Introduction

Here is the source code for SimpleQueueServiceMultiThread.java

Source

/*
 * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License").
 * You may not use this file except in compliance with the License.
 * A copy of the License is located at
 *
 *  http://aws.amazon.com/apache2.0
 *
 * or in the "license" file accompanying this file. This file is distributed
 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 */
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.ClientConfiguration;
import com.amazonaws.Protocol;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.sqs.AmazonSQS;
import com.amazonaws.services.sqs.AmazonSQSAsyncClient;
import com.amazonaws.services.sqs.AmazonSQSClient;
import com.amazonaws.services.sqs.model.CreateQueueRequest;
import com.amazonaws.services.sqs.model.DeleteMessageRequest;
import com.amazonaws.services.sqs.model.DeleteQueueRequest;
import com.amazonaws.services.sqs.model.Message;
import com.amazonaws.services.sqs.model.ReceiveMessageRequest;
import com.amazonaws.services.sqs.model.SendMessageRequest;

/**
 * This sample demonstrates how to make basic requests to Amazon SQS using the
 * AWS SDK for Java.
 * <p>
 * <b>Prerequisites:</b> You must have a valid Amazon Web
 * Services developer account, and be signed up to use Amazon SQS. For more
 * information on Amazon SQS, see http://aws.amazon.com/sqs.
 * <p>
 * Fill in your AWS access credentials in the provided credentials file
 * template, and be sure to move the file to the default location
 * (~/.aws/credentials) where the sample code will load the credentials from.
 * <p>
 * <b>WARNING:</b> To avoid accidental leakage of your credentials, DO NOT keep
 * the credentials file in your source directory.
 */
public class SimpleQueueServiceMultiThread implements Callable<Long> {

    private static long minTime, maxTime, totalTime, averageTime = 0L;
    private static int poolSize = 10;
    private static int threadSize = 10000;

    private static AmazonSQS sqs = null;
    private static String myQueueUrl = "https://sqs.ap-southeast-1.amazonaws.com/447332739387/SYS1_SYS2_MSGTYPE1";

    public static void main(String[] args) throws Exception {

        /*
         * The ProfileCredentialsProvider will return your [default]
         * credential profile by reading from the credentials file located at
         * (~/.aws/credentials).
         */
        AWSCredentials credentials = null;
        try {
            credentials = new ProfileCredentialsProvider().getCredentials();
        } catch (Exception e) {
            throw new AmazonClientException("Cannot load the credentials from the credential profiles file. "
                    + "Please make sure that your credentials file is at the correct "
                    + "location (~/.aws/credentials), and is in valid format.", e);
        }
        //AmazonSQS sqs = new AmazonSQSClient(credentials,clientConfig);
        sqs = new AmazonSQSClient(credentials);

        Region apSouthEast1 = Region.getRegion(Regions.AP_SOUTHEAST_1);
        sqs.setRegion(apSouthEast1);

        System.out.println("===========================================");
        System.out.println("Getting Started with Amazon SQS");
        System.out.println("===========================================\n");

        //Define thread pool size
        ExecutorService executor = Executors.newFixedThreadPool(poolSize);

        //create a list to hold the Future object associated with Callable
        List<Future<Long>> list = new ArrayList<Future<Long>>();

        //Create Callable instance
        Callable<Long> callable = new SimpleQueueServiceMultiThread();

        for (int i = 0; i < threadSize; i++) {

            //submit Callable tasks to be executed by thread pool
            Future<Long> future = executor.submit(callable);

            //add Future to the list, we can get return value using Future
            list.add(future);

        }

        for (Future<Long> fut : list) {

            try {
                // Future.get() waits for task to get completed
                System.out.println("Time difference : " + fut.get());

                long timeDiff = fut.get().longValue();

                totalTime = Long.valueOf(totalTime + timeDiff);

                if (timeDiff >= maxTime) {
                    maxTime = timeDiff;
                }

                if (minTime == 0L && timeDiff >= minTime) {
                    minTime = timeDiff;
                    //}else if (timeDiff <= minTime && timeDiff != 0L) {
                } else if (timeDiff <= minTime) {
                    minTime = timeDiff;
                }

            } catch (InterruptedException | ExecutionException e) {

                e.printStackTrace();

            }
        }

        if (totalTime >= 0L) {

            averageTime = totalTime / threadSize;

        }

        System.out.println("Total Time : " + Long.valueOf(totalTime).toString());
        System.out.println("Max Time : " + Long.valueOf(maxTime).toString());
        System.out.println("Min Time : " + Long.valueOf(minTime).toString());
        System.out.println("Average Time : " + Long.valueOf(averageTime).toString());

        //shut down the executor service now
        executor.shutdown();

    }

    @Override
    public Long call() throws Exception {

        Long transformTimeDiff = 0L;

        long startDate = System.currentTimeMillis();

        try {

            System.out.println("Sending a message to MyQueue.\n");
            sqs.sendMessage(new SendMessageRequest(myQueueUrl, "This is my message text."));

        } catch (AmazonServiceException ase) {
            System.out.println("Caught an AmazonServiceException, which means your request made it "
                    + "to Amazon SQS, but was rejected with an error response for some reason.");
            System.out.println("Error Message:    " + ase.getMessage());
            System.out.println("HTTP Status Code: " + ase.getStatusCode());
            System.out.println("AWS Error Code:   " + ase.getErrorCode());
            System.out.println("Error Type:       " + ase.getErrorType());
            System.out.println("Request ID:       " + ase.getRequestId());
        } catch (AmazonClientException ace) {
            System.out.println("Caught an AmazonClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with SQS, such as not "
                    + "being able to access the network.");
            System.out.println("Error Message: " + ace.getMessage());
        }

        long endDate = System.currentTimeMillis();

        transformTimeDiff = Long.valueOf(endDate - startDate);

        return transformTimeDiff;
    }
}