The purpose of concurrent programming is to make the program run faster, but it is not the more threads that start up that will allow the program to execute at maximum concurrency. Concurrent programming presents a number of challenges, such as context switching issues, deadlock issues, and resource constraints constrained by various hardware and software.
The CPU loops through the time slice allocation algorithm to perform the task, and the current task executes one time after the next task is switched. However, the status of the previous task is saved before switching, so that the next time you switch back to the task, you can load the status of the task again. The process of saving from a task to reloading is a context switch.
Vmstat 1#vmstat can test the number of context switches. The CS (Content switch) in the output indicates the number of context switches.
The methods for reducing context switching are: lock-free concurrent programming, CAS algorithm, using minimal threads, and using the co-process.
Use least threads: Avoid creating unwanted threads, such as fewer tasks, but creating many threads to handle, resulting in a large number of threads waiting (waiting).
Co-process: Multi-tasking scheduling in single thread, and the switch between multiple tasks in a single thread.
Hardware resources limit the bandwidth of upload/download speed, hard disk read and write speed and CPU processing speed. Software resources limit the number of connections to the database and socket connections.
How can i solve the problem of resource limitations?
For hardware limitations, you might consider using a cluster to execute programs in parallel. For example, using a Hadoop cluster, different machines process different data. A machine number can be calculated by "Data id%", and the data is processed by the corresponding numbered machine.
For software limitations, consider using a resource pool to reuse resources. For example, use connection pooling to reuse database and socket connections.
The challenges of Java concurrency programming