Java concurrent programming (concept)

Concurrency issues

In a Java program, all threads share main memory, but each thread has its own working memory (a virtual concept, including registers, stacks, write buffers, caches, etc.), and working memory interacts with main memory to synchronize data , And threads can only access their own working memory, so in a multi-threaded environment, it is easy to cause inconsistencies in working memory data and cause concurrency problems.

In addition, there is a problem of thread synchronization among multiple threads, that is, how to communicate and cooperate between threads.

Thread-safe

When multiple threads access an object, if you do not need to consider the scheduling and alternate execution of these threads in the runtime environment, there is no need for additional synchronization, or any other coordinated operation on the caller, the behavior of calling this object is The correct result can be obtained, then this object is thread safe.

Reorder

In order to improve performance when executing programs, compilers and processors often reorder instructions:

  • Compiler optimized reordering: You can rearrange the execution order of statements without changing the semantics of single-threaded programs.

  • Instruction-level parallel reordering: If there is no data dependency, the processor can change the execution order of the machine instructions corresponding to the statement.

  • Memory reordering: Since the processor uses cache and read / write buffers, the load and store operations may appear to be performed out of order.

These basic levels of reordering will follow the following specifications to ensure the correctness of the program:

  • Data dependency: For example, there is a data dependency between two operations that have a read-write relationship, but the data dependency in the case of multithreading is not considered.

  • as-if-serial semantics: no matter how to reorder, the execution result of single-threaded program will not be changed.

The reordering of the compiler and reordering does not consider the situation of multithreading and multiprocessors, so it will cause unpredictable problems in a concurrent environment.

Volatile keywords

Visibility: The semantics of this keyword ensure that the new value can be synchronized to the main memory immediately, and refreshed from the main memory immediately before each use.

Ordering: A memory barrier can be created (instruction reordering cannot reorder subsequent instructions to the position before the memory barrier) to prohibit instruction reordering.

Concurrency tools

  • Lock: Mutually exclusive synchronization.

    • synchronized: It seems to be omnipotent, but omnipotent things are usually accompanied by performance problems.

    • Reentrantlock: more flexible, and has the characteristics of waiting to be interrupted, fair lock can be achieved, and multiple conditions can be bound.

      • Waiting can be interrupted: When the thread holding the lock does not release the lock for a long time, the waiting thread can give up waiting and handle other things instead.

      • Fair lock: When multiple threads are waiting for the same lock, they must acquire the locks in sequence according to the time sequence of applying for the locks. Synchronized locks are unfair, that is, when the lock is released, any waiting thread has a chance to obtain the lock. Reentrantlock is also unfair by default, but it can be configured as a fair lock.

      • Bind multiple conditions: In synchronized, wait, notify or notifyAll of the lock object can implement an implicit condition. If you want to associate with more than one condition, you have to add an additional lock. Reentrantlock can bind multiple conditions through the newCondition method.

      In addition, Reentrantlock can communicate between threads through await and signal of the onition.

  • CAS: Compare And Swap, a mechanism similar to optimistic locking, each time it is updated, the old value is compared with the current value, and if they are the same, the update is performed, otherwise retry until success.

  • ThreadLocal: The ThreadLocal class solves the data isolation, that is, the data in multiple threads in the ThreadLocal will not interfere with each other, and only their own data is taken when they are taken out.

  • Immutable objects.

  • AQS, Abstract Queued Synchronizer, based on CAS to ensure thread safety, a class of Java concurrent package, provides some template methods.

synchronized与volatile

  • volatile is a lightweight implementation of thread synchronization, and its performance is better than synchronized. With the optimization of JDK 6 version, the efficiency of synchronized has been greatly improved, and it is used more in development.

  • volatile modified variables, synchronized modified methods, code blocks.

  • Multi-threaded access to volatile will not block, while synchronized will block.

  • Volatile can guarantee the visibility of data, but cannot guarantee the atomicity; synchronized can guarantee the atomicity, or indirectly guarantee the visibility, because it will synchronize the data in private memory and public memory.

Concurrent collection

Concurrent collection refers to the collection class under java.util.concurrent, the following are commonly used:

  • ConcurrentHashMap: A thread-safe version of HashMap, which has higher performance than the synchronization methods in Collections.

  • CopyOnWriteArrayList: a thread-safe version of ArrayList, a persistent data structure, that is, when writing to the list, a copy of the original list will be used for operation.

  • LinkedBlockngQueue: blocking queue implementation.

Synchronizer

  • CountDownLatch: You can implement counter-like functions.

  • CycliBarrier: A loopback barrier, which allows a group of threads to wait for a certain state and then execute them all at once.

  • Semphore: Semaphore, which controls the number of simultaneous access threads. Acquire permission through acquire (), and release a permission through release ().

Concurrency framework

  • Executor

  • Fork/Join

  • Actor

Suggestions for concurrent programming

  • Naming the thread can help debugging.

  • Use immutable classes, all attributes and classes are final immutable, which can ensure thread safety.

  • Always acquire multiple locks in a global fixed order to avoid deadlocks.

  • Minimize the synchronization range.

  • Segment lock.

  • Use volatile instead of synchronized.

  • Use higher-level concurrency tools instead of wait and notify to implement thread communication, such as BlockingQueue, CountDownLatch, and Semeaphore.

  • In high concurrency scenarios, it is best to use various frameworks cautiously and go directly to the Servlet.

Guess you like

Origin www.cnblogs.com/asleaf/p/12678139.html