Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I have a dual core machine. In java, how is a fixedThreadPool of 3 threads managed by my computer? What is a possible behavior of the jvm?

I'm trying to visualize how my machine would behave with this code if its a dual core processor. How would it behave if it were a quad core machine?

    ExecutorService executor = Executors.newFixedThreadPool(3);

    // Submission of tasks
    for (int i =0; i<10; i++){
        executor.submit(new Processor(i));
    }

The Processor has a run method that prints "running in thread: about to sleep..." Then it sleeps for 5 seconds then prints "running in thread: woke up..."

I'm trying to connect the dots between java code and hardware. I'm having difficulty picturing how this differs in different processor environments. Could someone give an example of a possible behavior of the jvm in this situation? Thank you in advance.

like image 734
Horse Voice Avatar asked Oct 01 '22 18:10

Horse Voice


1 Answers

The answer to each of your questions is, "yes". Or, to be less coy, the behavior you are asking for us to document is undefined very deliberately only loosely defined.

The JVM and O/S, working together are free to run your threads in any order at any time, on whatever CPU/core is available when they are eligible to run, provided they sleep for at least 5 seconds between the running and woke up messages. Due to the nature of sleep, it will be at least that time, and the thread will awake as close to that time as the scheduler can manage.

Beyond that, there's not much more that can be said.


In response to the comment, the question's code will add 10 items to a task queue, and will dequeue up to three at a time(*) and run each group of three concurrently.

Because the execution time is dominated by the sleep, the behavior will be essentially identical no matter how many cores are available.

However, the exact order in which things will happen is non-deterministic, beyond the fact that the tasks will be pulled off in the order added. So while you can be certain that the 10th task will execute after the 1st, you can't be certain about the ordering of 1, 2 and 3, nor whether 4, 5 or 6 might start before 1, 2 or 3 has entirely finished.

(*) Up to three, because the last group will have only two items and the third thread will be idle while they run.

like image 158
Lawrence Dol Avatar answered Oct 05 '22 06:10

Lawrence Dol