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

后端 未结 4 1826
慢半拍i
慢半拍i 2020-12-18 14:11

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?

相关标签:
4条回答
  • 2020-12-18 14:40

    On the flip of that, it is sometimes useful to "bound"/set affinity for a Java process to only use a set of cores/sockets, though done via OS semantics. As previously answered, most runtimes indeed employ all cpus and with highly threaded apps can eat up more resources than you might expect.

    0 讨论(0)
  • 2020-12-18 14:42

    All modern JVMs will take advantage of as many cores as your hardware has. An easy way to illustrate this is to download and run the DaCapo benchmark on your machine. The lusearch benchmark uses 32 threads. If you run this on your desktop or server, you should see all of your CPUs hit 100% utilization during the test.

    0 讨论(0)
  • 2020-12-18 14:46

    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();
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-18 14:52

    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.

    0 讨论(0)
提交回复
热议问题