The art of Java concurrent programming, notes (1) – challenges of concurrent programming

Context switching

  1. Meaning
    CPU implements multithreading by assigning time slices to each thread. The time slice is usually tens of milliseconds. When the task time slice is used up, it cuts to the next task, but the state of the last task is saved before switching, so that the task can be reloaded when the task is switched back. The task from the save state to the reload process is a context switch.
  2. How to reduce context switching
    (1) lock free concurrent programming. If the data is properly segmented, different threads handle different segments of data.
    (2) CAS algorithm. Java’s Atomic package uses the CAS algorithm without locking.
    (3) avoids creating unnecessary threads.
    (4) consensus.

Two, deadlock

A common way to avoid deadlocks:
(1) prevents a thread from acquiring multiple locks simultaneously.
(2) prevents a thread from occupying more than one resource within a lock.
(3) attempts to use timing locks, trylock, etc..
(4) for database locks, locks and unlocks must be in a database connection.

Three, others

(1) thread.join ()
waits until the thread is executed and continues to execute the current thread.