Matt
Matt

Reputation: 2663

Java: Sending messages to a JMS queue with multiple threads

I am trying to write a Java class to both send and read messages from a JMS queue using multiple threads to speed things up. I have the below code.

    System.out.println("Sending messages");
    long startTime = System.nanoTime();

    Thread threads[] = new Thread[NumberOfThreads];
    for (int i = 0; i < threads.length; i ++) {
        threads[i] = new Thread() {
            public void run() {
                try {
                    for (int i = 0; i < NumberOfMessagesPerThread; i ++) {
                        sendMessage("Hello");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        threads[i].start();
    }

    //Block until all threads are done so we can get total time
    for (Thread thread : threads) {
        thread.join();
    }

    long endTime = System.nanoTime();
    long duration = (endTime - startTime) / 1000000;
    System.out.println("Done in " + duration + " ms");

This code works and sends however many messages to my JMS queue that I say (via NumberOfThreads and NumberOfMessagesPerThread). However, I am not convinced it is truly working multithreaded. For example, if I set threads to 10 and messages to 100 (so 1000 total messages), it takes the same time as 100 threads and 10 messages each. Even this code below takes the same time.

    for (int i = 0; i < 1000; i ++) {
        sendMessage("Hello");
    }

Am I doing the threading right? I would expect the multithreaded code to be much faster than just a plain for loop.

Upvotes: 3

Views: 5270

Answers (2)

Calanais
Calanais

Reputation: 1580

I would also review some of the comments in this post Single vs Multi-threaded JMS Producer

What is the implementation of 'sendMessage'. How are the connections, session, and producers being reused?

Upvotes: 1

Claudio
Claudio

Reputation: 1858

Are you sharing a single connection (a single Producer) across all threads? If so then probably you are hitting some thread contention in there and you are limited to the speed of the socket connection between your producer and your broker. Of course, it will depend much on the jms implementation you are using (and if you are using asyncSends or not).

I will recommend you to repeat your tests using completely separate producers (although, you will lose the "queue" semantic in terms of ordering of messages, but I guess that is expected).

Also, I do not recommend running performance tests with numbers so high like 100 threads. Remember that your multithread capability it at some point limited by the amount of cores you machine has (more or less, you are having also a lot of IO in here so it might help to have a few more threads than cores, but a 100 is not really a good number in my opinion)

Upvotes: 5

Related Questions