I remember that when I started to learn JAVA, I was weakest in concurrency. I could only do some simple multithreading and the use of locks. I didn’t think about it at the bottom.

Context switch

A context switch is the process of a task from saving to reloading, because the processor supports multi-threaded code execution by allocating CPU time slices to each thread. Since the time slices are very short, the CPU keeps switching threads of execution, giving us the feeling that multiple threads are executing at the same time. The CPU circulates tasks through the time slice allocation algorithm. After the current task executes a time slice, it switches to the image task. Before switching, the state of the previous task will be saved, and the task state will be loaded when the task is switched back next time. When the number of concurrent operations is not reached, the concurrent execution speed is slower than the serial execution speed. This is because of the overhead of threading and context switching

Reduce context switching

Context switching can be reduced by using lock-free concurrent programming, CAS algorithms, using minimal threads, and using coroutines.

  • Lockless concurrent programming such as the ID of the data according to the Hash algorithm modular segmentation, different threads processing different segments of the data.
  • The CAS algorithm, which stands for compare and replace, is used to update data without locking in the Java Atomic package.
  • Use the minimum number of threads to avoid creating unnecessary threads, and avoid creating too many threads and leaving too many threads in the wait state.
  • The coroutine implements the scheduling of multiple tasks in a single thread and maintains the switching of multiple tasks in a single thread.

A deadlock

Deadlock in my understanding is that in A locked thread 1 you need to use the object using the object B first, in another locked thread 2 object B first, then using the object will be used inside A, start at the same time, the thread 1 lock objects A, thread 2 lock object B, cause the thread one waiting thread to release 2 B, At the same time, thread 2 waits for thread 1 to release A, so the two threads are waiting for each other to release the lock

The Art of Concurrent Programming in Java

My humble opinion, thank you for reading. Welcome to the discussion,Personal blog

JAVA concurrency (1) Concurrency programming challenges

JAVA concurrency (2) Underlying implementation principles of synchronized and volatile

JAVA concurrency (3) lock status

JAVA concurrency (4) atomic operation implementation principle

JAVA concurrency (5) happens-before

JAVA concurrency (6) reordering

JAVA concurrency (7) Analyze volatile against the JMM

JAVA concurrency (8) Final domain

JAVA concurrency (9) In-depth analysis of DCL

JAVA Concurrency (10) Concurrency programming basics