(1) concurrent programming Java concurrent programming artistic challenge

Why concurrent programming

Concurrent programming is designed to make the program run faster. Concurrent programming problems encountered, context switching problem, deadlock, and the resources limited by hardware and software constraints.

Context switching

It will switch to the next task allocation algorithm by the CPU cycles to perform the task time slice, a time slice of the current task execution. However, before switching will be retained on a task of the state to the next state to switch back to the task, you can then load this task. So the task is to save a context switch from the process of reloading.

How to reduce context switching

(1) without concurrent programming locks: locks when competition multithreading, can cause a context switch, the multi-threaded processing of data, some of the approach can be used to avoid the use of a lock, such as the ID data in accordance with Hash algorithm modulo segment, different threads processing data in different segments.
(2) Algorithm CAS: Java package using the Atomic CAS algorithm to update the data, does not require locking.
(3) with a minimum thread: avoid creating unwanted threads, such as small task, but creating a lot of threads to handle, this will cause a large number of threads are in a wait state
(4) coroutines: In a single-threaded multi-task scheduling in and maintain switching between multiple tasks in a single thread.

Deadlock

Thread t1 and t2 threads waiting for each other to release the lock, causing some functions can not be used, once the deadlock, the business is perceived, because u can not continue to provide services, and can be viewed by dump thread which thread in the end is a problem.

Several common method of avoiding deadlock

(1) acquiring a plurality of threads to avoid a lock
(2) to avoid a plurality of threads simultaneously occupy resources in the lock, each lock occupies only try to ensure that a resource
(3) using the timing of the attempt, using lock.tryLock (timeout) instead of using internal locking mechanism
(4) must be connected to a database, otherwise the situation would appear to fail to unlock the database locks, locking and unlocking

Published 24 original articles · won praise 1 · views 550

Guess you like

Origin blog.csdn.net/qq_45366515/article/details/105092436