Farzad
Farzad

Reputation: 1929

Multi-thread performance in Java when working with a list


I'm new to the multi-threading concept and I'm creating a simple Java program to experience with multiple threads and stuff.
In my program, I simply have a linked list, and I create a thread to just remove list items from the beginning. I implement the Runnable interface and this is what the run method of my thread looks like: (I set list in the constructor)

public void run() {
    System.out.println("Starting...");

    while (!list.isEmpty()) {
        synchronized (list) {
            list.removeFirst();             
        }
    }

    System.out.println("Finished!");
}


In the main method, I add a huge number of items to the linked list (10,000,000) and simply create instances of this class to run concurrently and I measure the time:

    Thread my1 = new Thread(new MyThread("my1", list));
    Thread my2 = new Thread(new MyThread("my2", list));
    Thread my3 = new Thread(new MyThread("my3", list));

    startTime = System.currentTimeMillis();
    my1.start();
    my2.start();
    my3.start();
    my1.join();
    my2.join();
    my3.join();
    endTime = System.currentTimeMillis();
    elapsedTime = endTime - startTime;

    System.out.println("Main finished in " + elapsedTime + " milliseconds.");


Interestingly enough, when I run my program using these 3 threads, I receive the message:

Main finished in 444 milliseconds


But, when I use only a single thread, I receive the message:

Main finished in 223 milliseconds


Is there anyway I can tweak the code to run actually faster when using multiple threads???

Thank you in advance

Upvotes: 0

Views: 317

Answers (2)

You've run into what's called the critical path, the portion of the code that has to be be properly ordered and thus can't be parallelized. In this example, the critical path is most of your program, so you won't gain anything by trying to use multiple threads. Multiple threads provide a benefit only when they do a substantial amount of work (I/O, localized computation) that's independent.

Upvotes: 0

Justin Kaeser
Justin Kaeser

Reputation: 5948

This example cannot benefit from multiple threads, on the contrary: You are adding overhead by synchronizing access to the list, so that only one thread can access it at a time. While this is necessary for correctness, the actual operation is so low-overhead that the synchronization dominates.

This scenario could make sense if your worker threads did some expensive computation or I/O with the data from the list. If that is the actual goal, you should include this in your benchmark.

Upvotes: 2

Related Questions