Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Would a multithreaded Java application exploit a multi-core machine very well?

If I write a multi-threaded java application, will the JVM take care of utilizing all available cores? Do I have to do some work?

like image 740
tilish Avatar asked May 22 '26 04:05

tilish


2 Answers

Unless you use a JVM that has so-called "green" threads (which is very few these days), Java threads are run by OS threads, so multiple threads get run on different cores by default.

like image 64
Nat Avatar answered May 24 '26 01:05

Nat


To follow up, I see 100% usage on both cores when I run this code on my dual core. If I bring the number of threads from two to one, one core goes to 100% and another about 4%.

package test;

import java.util.ArrayList;

public class ThreadTest
{
    public void startCPUHungryThread()
    {
        Runnable runnable = new Runnable(){
            public void run()
            {
                while(true)
                {
                }
            }
        };
        Thread thread = new Thread(runnable);
        thread.start();     
    }

    public static void main(String[] args)
    {
        ThreadTest thread = new ThreadTest();
        for (int i=0; i<2; i++)
        {
            thread.startCPUHungryThread();
        }
    }
}
like image 44
tilish Avatar answered May 24 '26 02:05

tilish



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!