First, security issues

  1. The essence of thread safety is correctness, and correctness means that the program executes as expected

  2. Theoretically thread-safe programs should avoid visibility problems (CPU caching), atomicity problems (thread switching), and orderliness problems (compiler optimization)

  3. Scenarios where thread-safety issues need to be analyzed: data is shared and changes, that is, multiple threads read and write the same data at the same time

  4. The solution to this theory: do not share data, using Thread Local Storage (TLS); The same pattern

ⅰ. Data competition

Data Race: Multiple threads access the same Data at the same time and at least one thread writes to the Data

1. add

private static final int MAX_COUNT = 1_000_000; private long count = 0; // non-thread-safe public voidadd() {
    int index = 0;
    while(++index < MAX_COUNT) { count += 1; }}Copy the code

2. add + synchronized

private static final int MAX_COUNT = 1_000_000;
private long count = 0;
public synchronized long getCount() {
    return count;
}
public synchronized void setCount(long count) { this.count = count; } // non-thread-safe public voidadd() {
    int index = 0;
    while (++index < MAX_COUNT) {
        setCount(getCount() + 1); }}Copy the code
  • Assuming count=0, when both threads execute getCount() at the same time, both threads return 0
  • A race condition occurs when two threads execute getCount()+1, both get 1, and end up writing 1 to memory, not as expected

ⅱ. Race condition

  1. Race Condition: The execution result of a program depends on the order in which the threads execute
  2. In a concurrent environment, the order of execution of threads is uncertain
    • If a program has a race condition problem, it means that the execution result of the program is uncertain

1. The transfer

public class Account { private int balance; Public void Transfer (Account target, int amt) {if(balance > amt) { balance -= amt; target.balance += amt; }}}Copy the code

ⅲ. Solutions

In the face of data contention and race condition problems, thread safety can be realized by mutual exclusion, which can be unified as locks

Two. Activity problem

Activity problem: an operation cannot be executed. There are three conditions: deadlock, live lock, and starvation

Ⅰ. Deadlocks

  1. After a deadlock occurs, threads wait for each other, which is permanently blocked
  2. The solution to deadlocks isAvoid deadlock(One of the conditions for breaking a deadlock)
    • Mutually exclusive: Unbreakable, locked for mutually exclusive purposes
    • Hold and wait: Request all required resources at once
    • Non-preemption: When A thread holding resource A fails to hold resource B, the thread actively releases resource A
    • Circular waiting: Resources are numbered in order. Threads apply for resources in ascending (or decreasing) order

Live Ⅱ. Lock

  • Live lock: a thread that is not blocked but fails to execute due to mutual concessions
  • Solution: Try to wait for a random amount of time while conceding (distributed consistency algorithm Raft is also used)

Ⅲ hunger.

  1. hunger: The thread cannot execute because it cannot access the required resource
    • Threads have different priorities, and when the CPU is busy, threads with lower priorities have less opportunity to execute, and thread starvation can occur
    • Threads holding locks can also cause starvation problems if they take too long to execute (holding resources that are not released)
  2. The solution
    • Ensure adequate resources
    • Fair allocation of resources (fair locking) – feasible
    • Prevent the thread holding the lock from executing for long periods

Third, performance issues

  1. Excessive use of locks can lead to excessive serialization, which can take advantage of multithreading (the purpose of concurrent programs is to improve performance)
  2. Minimize serialization, it is assumed thatSerial percentageIt’s 5%, soMulti-core multithreadingRelative to theSingle core single threadAmdahl’s Law of Lifting

    S=1/((1-p)+p/n), n is the number of CPU cores, p is the parallel percentage, and (1-p) is the serial percentage
    • Suppose p=95%, n is infinite, and the limit of acceleration ratio S is 20, i.e., no matter what technology is used, the performance can only be improved by a maximum of 20 times

ⅰ. Solutions

  1. Lock-free algorithms and data structures
    • Thread Local Storage (TLS)
    • Copy-on-write
    • Optimistic locking
    • Atomic classes in JUC
    • Disruptor (Memory queue without lock)
  2. Reduce lock holding time. The essence of mutex is to serialize parallel programs. To increase parallelism, you must reduce lock holding time
    • Use fine-grained locks, such as ConcurrentHashMap in JUC
    • With read/write locks, that is, reads are unlocked and only writes are mutually exclusive

ⅱ. Performance Indicators

  1. Throughput: The number of requests that can be processed per unit time. The higher the throughput, the better the performance
  2. Latency: The time from sending a request to receiving a response. The smaller the latency, the better the performance
  3. Concurrency: The number of requests that can be processed at the same time. Generally, as the number of concurrent requests increases, the latency increases, so the latency is generally based on the number of concurrent requests

The last

Like you can pay attention to my public number, Java small melon brother sharing platform, usually organized data are put in it