[Concurrent programming - foundation] (ix) multi-threaded extension

A deadlock

1.1 What is a deadlock

       Two or more processes in the implementation process to wait for each other's resources due to competition caused by another phenomenon, if there is no external force, they will be unable to continue, which said the system is in deadlock state or system parameters dead lock this kind of waiting another process, called the process deadlock.

1.2, a necessary condition for the occurrence of deadlock

       1.2.1, exclusive mutually exclusive conditions of use

       Exclusive use mutually exclusive conditions, that is a resource that only one process over a period of time occupied, at this time if there are other resources to process the request, then the requestor can only wait until the process runs out of resources possession, released before they can process to be allocated resources.

       1.2.2, and the request holding condition

       The process has been maintained for at least one resource, but the heart of the proposed resource requests, and the resource has been occupied by other processes, this time requesting process blocked, but for other resources that they have available to keep hold.

       1.2.3, not deprivation

       Resource refers to the process have been obtained before is not used, can not be denied, our only released when you are finished.

       1.2.4 loop wait condition

       When a deadlock occurs, the resource deadlocks between processes must be a circular chain.

       1.2.5, concurrent coding principles

       Always log in or lock in place concurrent

1.3, to achieve a deadlock

       1.3.1 Code
@Slf4j
public class DeadLock implements Runnable {
    public int flag = 1;
    //静态对象是类的所有对象共享的
    private static Object o1 = new Object(), o2 = new Object();

    @Override
    public void run() {
        log.info("flag:{}", flag);
        if (flag == 1) {
            synchronized (o1) {
                try {
                    //等待500ms防止该进程运行太快,另一个进程还没进入
                    Thread.sleep(500);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                synchronized (o2) {
                    log.info("1");
                }
            }
        }
        if (flag == 0) {
            synchronized (o2) {
                try {
                    //等待500ms防止该进程运行太快,另一个进程还没进入
                    Thread.sleep(500);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                synchronized (o1) {
                    log.info("0");
                }
            }
        }
    }

    public static void main(String[] args) {
        DeadLock td1 = new DeadLock();
        DeadLock td2 = new DeadLock();
        td1.flag = 1;
        td2.flag = 0;
        //td1,td2都处于可执行状态,但JVM线程调度先执行哪个线程是不确定的。
        //td2的run()可能在td1的run()之前运行
        new Thread(td1).start();
        new Thread(td2).start();
    }
}
       1.3.3, the cause deadlock
  • When the object flag == DeadLock class 1 (td1), the first locking o1, 500 ms sleep
  • The td1 another flag == 0 objects (td2) thread starts during sleep when the first lock o2, sleep 500 milliseconds
  • After td1 sleep needs to be locked to o2 continues, but this time td2 o2 has been locked;
  • After td2 sleep need to lock o1 to continue, but this time td1 o1 has been locked;
  • td1, td2 wait for each other, we need to get each other to lock the resources to continue, thereby deadlock.

1.4 to detect whether there is a deadlock

       1.4.1, the program can not be executed, and the CPU usage is 0

       In a real environment, we found that this is reason to suspect that a deadlock, but the suspicion is not enough light, we need a practical method of authentication.

       1.4.2, use the tools provided to detect whether jdk really happened deadlock.

(1) console input JPS
Here Insert Picture Description
(2) find the process deadlock doubt, my process id is 11860, enter jstack 11860
Here Insert Picture Description

1.5, to avoid deadlock

  • Note locking sequence (this is well understood, like the example above)
  • Locking time (over time to give up the lock)
  • Implementation - using the reentrant lock.
  • Deadlock detection (difficult, as the situation on top of the thread analysis)

Second, concurrent Best Practices

2.1, use local variables

       Should increase the use of local variables, rather than creating a class or instance variables, typically developers use object instance as a variable, you can save memory and can be reused in the case, because they believe that every time you create a local variable in local memory consumes method

2.2, immutable class

       Reducing the number of synchronization code

2.3, to minimize the lock scope range

       Formula: S = 1 / (1-a + a / n)

       is a proportion calculation section process, n being the number of parallel processing nodes, s represents (speedup)

       When 1-a = 0 when only this time no serial parallel, the maximum (speedup) S is equal to n. When a = 0 when only serial, not parallel, this time to a minimum (speedup) s = 1 when n tends to infinity, the limit (speedup) tends to 1:. 1-a, which is speedup on-line: Amdahl's Law

2.4, use the thread pool Executor rather than direct new Thread

       When you create a thread of the cost of expensive, if you want a scalable Java application, you will need to use the thread pool, thread pool to manage threads, jdk provides a variety of thread pool.

2.5, rather synchronous and do not use wait and notify methods thread

       From then Java1.5 increased the number of synchronization tools can also be used to implement threads wait countdownlash

2.6, using BlockingQueue achieve the production - consumption patterns

       Most concurrency model can be used to achieve design production and consumption, and BlockingQueue is the best way to achieve, blocking queue only to achieve a single production of a single consumer can also handle multiple production and consumption

2.7, instead of using the concurrent collections plus a set of synchronization locks

       There are five concurrent collections copy ..., do not use the synchronization lock collection connections.sync

2.8, use Semaphore to create bounded access

       In order to establish a reliable and stable system for the database file system and socked and other resources must be done orderly access. Semaphore is a selection of these resources to limit overhead, if a resource can not be used Semaphore, can wait at minimum cost block the thread, we can control the number of threads simultaneously access the specified resource by Semaphore

2.9, rather synchronous block, nor a method of synchronizing

       For the synchronized keyword, use the keyword synchronized block will lock an object, rather than locking the entire method, if you change a variable or class of common fields first choice
is the atomic variable and then use XXXX, if you need a mutex you can use the lock to speak above.

2.10, avoid the use of static variables

       Static variables are a lot of problems in the case of concurrent execution, if you must use a static variable, then the priority it called final variable, if it is used to store a collection of connection, then it can be considered read-only collection, otherwise it must be done particularly synchronous processing and concurrent processing.

Three, Spring and thread safety

       Spring bean :singleton、prototype

       Stateless object (Service, Controller, Dao stateless, is used to perform certain operations)

Four, HashMap

4.1, HashMap structure

  • Through the array and pointer reference implementation.
  • Initialization time can pass two values, one for the initial capacity and load factor

4.2, hashmap expansion

4.2.1, the expansion of existing hashmap thread-safety issues

hashmap expansion there is thread-safety issues rehash

Expansion of operating without problem (1) single-threaded case
Here Insert Picture Description
(2) expansion of the operation will appear endless loop pointer multiple threads
Here Insert Picture Description

4.2.2, ConcurrentHashMap solve the issue on appeal

Here Insert Picture Description

4.2.3 difference, ConcurrentHashMap with the HashMap
  • ConcurrentHashMap is thread-safe, hashmap not thread-safe.
  • HashMap allows key and value is empty, ConcurrentHashMap not allowed
  • Java7 achieve lock segment, Java8 cancel the lock segment, using red-black tree
  • See the figure red-black tree

Here Insert Picture Description

Published 20 original articles · won praise 1 · views 557

Guess you like

Origin blog.csdn.net/weixin_42295814/article/details/103792786