Andreas Hornig Andreas Hornig - 6 months ago 5x
Java Question

Java: How to scale threads according to cpu cores?

I'm not a good java programmer, it's just my hobby, but I'm eager to know more than average stuff.

I want to solve a mathematical problem with multiple threads in java. my math problem can be separated into work units, that I want to have solved in several threads.

but I don't want to have a fixed amount of threads working on it, but instead a coresponding amount of threads to the amount of cpu cores.
and my problem is, that I couldn't find an easy tutorial in the internet for this. all I found are examples with fixed threads.

So could you help me with a link to a good tuturial or could give me an easy and good example? That would be really nice :)


You can determine the number of processes available to the Java Virtual Machine by using the static Runtime method, availableProcessors. Once you have determined the number of processors available, create that number of threads and split up your work accordingly.

Update: To further clarify, a Thread is just an Object in Java, so you can create it just like you would create any other object. So, let's say that you call the above method and find that it returns 2 processors. Awesome. Now, you can create a loop that generates a new Thread, and splits the work off for that thread, and fires off the thread. Here's some psuedocode to demonstrate what I mean:

int processors = Runtime.getRuntime().availableProcessors();
for(int i=0; i < processors; i++) {
  Thread yourThread = new AThreadYouCreated();
  // You may need to pass in parameters depending on what work you are doing and how you setup your thread.

For more information on creating your own thread, head to this tutorial. Also, you may want to look at Thread Pooling for the creation of the threads.