[Java] Finding the optimal number of threads

Source: Internet
Author: User

1. Preface

Recently asked a question, "I used Java to write a multi-threaded function, but the number of threads should be much better?" "。 This issue was previously heard in the version: "Twice times the number of CPU cores", "as the number of CPU cores", "CPU core number plus 1". But because of a "lazy" word to bury this question mark in the bottom of my heart. In order to give the story a perfect end, so there is this blog post.

2. Thread definition

Threads ( English: Thread) are the smallest unit in which the operating system is able to perform operational scheduling. It is included in the process and is the actual operating unit of the process. A thread refers to a single sequential control flow in a process in which multiple threads can be concurrent and each thread performs different tasks in parallel. threads are the basic unit of independent Dispatch and dispatch.

The benefits of using multithreaded programming on multicore or multi-CPU, or on CPUs that support hyper-threading, are obvious, which increases the execution throughput of the program. On a single CPU single-core computer, using multithreaded technology, can also be responsible for IO processing in the process, human-computer interaction and often blocked part of the dense computing part of the execution, writing a dedicated workhorse thread to perform dense computation, Thus, the execution efficiency of the program is improved.

3. Threading and Processor

We discuss the role of multithreading under the condition of a processor (single core). Figure 1 assumes a scenario in which a task handles a collection of blocks of data, where only one thread a,1 the first block of data, and 2 represents the second block of data. Thread A processes each block of data for a block of time. Only the thread a working part of the processor is used, that is, a block of data is not processed, and a portion of the computational resources are wasted.

(Fig. 1)

To take full advantage of the processor and speed up processing efficiency, we introduced multi-threading, 2. A total of three thread a,b,c. When thread a handles the first chunk of data that is blocked, thread B gets the right to use the processor to begin execution. Thread B also encounters a blocking, yielding processor. Thread a good luck to get the processor again after the execution continues ... Thread C Gets the processor right to execute its own code when it enters the block for the second time.

(Fig. 2)

The use of multithreading in the case of single-processor single-core in Figure 1 and Figure 2 makes full use of system computing resources and shortens the overall computing time of the task.

4. Theoretical basis for calculating the optimal number of threads

In the diagram above, perhaps you have questions, I this is only the task of the blocking part of the scene, the blocking part and the number of threads of the relationship is what?

Venkat Subramaniam, in the programming Concurrency on the JVM, mentions the calculation of the optimal number of threads, the following is the original:

The minimum number of threads is equal to the number of availablecores. If all of the tasks are computation intensive and then this is all we need. Havingmore threads would actually hurt in the case because cores would being contextswitching between threads when there is s Till. If tasks is iointensive, then we should has more threads.

We can compute the total number of threads we ' d need as follows:

Number of threads = number of Available cores/(1-blocking coefficient)

To determine the number of threads, we need to know, both things:
? The number of available cores
? The blocking coefficient of tasks


The first one is easy to determine; We can look up this information, even at
Runtime, as we saw earlier. It takes a bit of effort to determine the blocking
Coefficient. We can try to guess it, or we can use profiling Tools or the Java.
Lang.management API to determine the amount of time a thread spends on
System/io operations vs. on cpu-intensive tasks.

Blocking coefficient (blocking factor) = blocking time/(blocking time + time spent using the CPU)

5. Practice the Truth

The absorption of knowledge should not only stay in the book, the following sample code to verify the formula. Here is the code, followed by the statistics of the experimental results.

Stage class

 PackageCom.bob.testjava.thread;ImportJava.util.concurrent.CountDownLatch;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors;/*** Created by Zhangmingbo on 1/7/17.*/ Public classStage { Public Static voidMain (string[] args)throwsinterruptedexception {LongStartTime =System.currenttimemillis (); Executorservice ThreadPool=NULL; Try{ThreadPool=Executors.newfixedthreadpool (constants.thread_size); Countdownlatch Countdownlatch=NewCountdownlatch (constants.size);  for(inti = 0; i < constants.thread_size; i++) {Threadpool.execute (NewWorker (Countdownlatch));        } countdownlatch.await (); } Catch(Exception e) {e.printstacktrace (); } finally {            LongEndTime =System.currenttimemillis (); intCpucorenum =runtime.getruntime (). Availableprocessors (); System.out.println ("Number of CPU cores:" +cpucorenum); System.out.println ("Work Time" (millisecond): "+Constants.work_time_millisecond); System.out.println ("Block Time" (millisecond): "+Constants.block_time_millisecond); Double blockcoefficient= (Constants.block_time_millisecond * 1d)/(Constants.work_time_millisecond +Constants.block_time_millisecond); System.out.println ("Block coefficient:" +blockcoefficient); intOptimalthreadnum =NewDouble (Cpucorenum/(1-blockcoefficient)).            Intvalue (); System.out.println ("Optimal thread number in theory:" +optimalthreadnum); System.out.println ("Number of Task:" +constants.size); System.out.println ("Number of Thread:" +constants.thread_size); System.out.println ("Cost Time:" + (EndTime-startTime)); Try{threadpool.shutdownnow (); } Catch(Exception e) {} }}}

Worker class

 PackageCom.bob.testjava.thread;ImportJava.util.concurrent.CountDownLatch;/*** Created by Zhangmingbo on 1/7/17.*/ Public classWorkerImplementsRunnable {PrivateCountdownlatch Countdownlatch;  PublicWorker (Countdownlatch countdownlatch) { This. Countdownlatch =Countdownlatch; }     Public voidrun () {Try {             while(Countdownlatch.getcount () > 0) {                // do workTestutil.doworkbytime (Constants.work_time_millisecond); //Do block Operationtestutil.doblockoperation (Constants.block_time_millisecond);            Countdownlatch.countdown (); }        } Catch(Interruptedexception e) {} }}

Testutil class

 PackageCom.bob.testjava.thread;ImportJava.util.concurrent.TimeUnit;/*** Created by Zhangmingbo on 1/10/17.*/ Public classTestutil { Public Static voidDoworkbytime (Longmillisecond) {        LongStartTime =System.currenttimemillis ();  while(true) {            LongEndTime =System.currenttimemillis (); LongCosttime = EndTime-StartTime; if(Costtime >=millisecond) {                return; }        }    }     Public Static voidDoblockoperation (LongMillisecond)throwsinterruptedexception {TimeUnit.MILLISECONDS.sleep (millisecond); }}

Constants class

 PackageCom.bob.testjava.thread;/*** Created by Zhangmingbo on 1/7/17.*/ Public classConstants { Public Static Final intSIZE = 100;  Public Static Final intThread_size = 8;  Public Static Final LongBlock_time_millisecond = 5;  Public Static Final intWork_time_millisecond = 5;}

The above is the code used in this experiment, where the stage class as the scene class Main method is executed from here, using Countdownlatch to act as the data to be processed, its size determines how many task volume, when the task is finished, will print some information, such as: CPU logic core number, blocking factor, Task volume, total task time and so on. This creates the Testutil class, which provides a way for the class to emulate the CPU-hogging operation and the blocking part. The data for this execution can be counted by adjusting the parameters in the constants class. The worker class is the thread class for this experiment.

-----------------------------------------------------------------------Split Line------------------------------------- ------------------------------------------

Experimental Results data:

The result of the experiment was not the same as expected. According to the formula, the optimal number of threads should be 8, but the experimental results show that 8 is twice times or more. Perhaps it is in itself that my computer is still running other processes, or I write the program where unreasonable, this if a friend can help correct, greatly appreciated.

6. Summary

The process of finding the optimal number of threads is joyful, which comes from the joy of constantly acquiring knowledge. This blog post is not finished, there is still a mystery unsolved, first recorded:

Myth One: Multiple processes running in one server, calculating the optimal number of threads for a task in one process must be disturbed.

Riddle two: How to calculate the blocking factor of a task accurately?

7. References

Programming Concurrency on the JVM

Wikipedia

[Java] Finding the optimal number of threads

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.