JAVA concurrent system -3- concurrent containers

Copy-On-Write(COW)

Copy-On-Write short COW (not milk cows), is an optimization strategy for program design. Copy On Write technology has applications in Linux and file system, Linux Copy On Write technology by dramatically reducing the cost of Fork , the file system is guaranteed by Copy On Write technology to some extent on the integrity of the data . ( TODO: write an article dedicated to elaborate on this matter )

In the concurrent Java package also has his shadow, this section is described concurrent package Copy On Write technology.

The basic idea Copy-On-Write is, from the beginning we all shared the same content, when someone wants to modify the content, content Copy will really put out a new form of content and then change, which is one kind of delay lazy strategy .

concurrent assembly according to the COW package contains: a CopyOnWriteArrayList and CopyOnWriteArraySet

What is CopyOnWrite container

CopyOnWrite container that is copy-on-write vessel. From the beginning JDK1.5 Java concurrency package provides two mechanisms to achieve concurrent use CopyOnWrite container, they are CopyOnWriteArrayList and CopyOnWriteArraySet.

  • The process of adding elements:

    Popular understanding is that when we add elements to a container, do not add to the current container directly, but first current container Copy, copy a new container, and then add a new container element (adding process need to lock ), finished adding elements, then the original container references point to the new container.

  • advantage:

    It can be read concurrently on CopyOnWrite container without the need to lock, because the current container does not add any elements. Therefore CopyOnWrite container is also a separate read and write thinking , reading and writing of different containers.

  • Disadvantages:

    • Memory footprint issues

      When performing the write operation, the memory will also be stationed memory, old objects and object newly written two objects. If these objects occupy memory is relatively large, it will take up more resources, resulting in prolonged or frequent GC GC.

      Compression elements of the container or containers of other concurrent use , as ConcurrentHashMap

    • Data consistency problems

      Data can only guarantee eventual consistency, we can not guarantee real-time data consistency

  • Scenario:

    Reading and writing less concurrency scenarios. Examples such as:

    • Whitelist, blacklist
    • Merchandise category access and update scene
  • Library components: CopyOnWriteArrayList and CopyOnWriteArraySet

    And it was achieved CopyOnWriteArrayList CopyOnWriteArraySet AbstractSet List interface and an interface which comprises a CopyOnWriteArraySet CopyOnWriteArrayList instance field, thus achieving COW applications. So they are two similar behavior

The principle (read / write)

private boolean addIfAbsent(E e, Object[] snapshot) {
    final ReentrantLock lock = this.lock;
    lock.lock();
    try {
        Object[] current = getArray();
        int len = current.length;
        ......
        Object[] newElements = Arrays.copyOf(current, len + 1);// 复制出新数组
        newElements[len] = e; // 把新元素添加到新数组里
        setArray(newElements);// 把原数组引用指向新数组
        return true;
    } finally {
        lock.unlock();
    }
}
...
final void setArray(Object[] a) {
    array = a;//直接修改引用
}

The above code is written elements can be found in time to add is the need to lock in , otherwise the time will write multi-threaded Copy the N copies of it.

Read element when we do not need to lock , if there are multiple threads reading when data is added to the container, read or will read the old data , because the time to write not lock the old container

ConcurrentMap

all ConcurrentHashMap

todo: ConcurrentSkipListMap ==> ConcurrentSkipListSet

todo: talk concurrent (d) in-depth analysis ConcurrentHashMap

Multi-threaded environment, the use of Hashmap be put action will cause an infinite loop, resulting in CPU utilization close to 100%, so you can not use a HashMap in concurrency

When inefficient HashTable container, container HashTable using synchronized to ensure the security thread, other thread synchronization method HashTable access may be blocked or enter the polling state

Segmentation techniques locking ConcurrentHashMap

ConcurrentHashMap initialization

Positioning Segment

ConcurrentHashMap the get operation

ConcurrentHashMap size of the operation

ConcurrentLinkedQueue

all ConcurrentLinkedQueue

all ConcurrentLinkedDeque

Implement a thread-safe queue implemented in two ways: one is to use blocking algorithm, the other is to use non-blocking algorithms.

Using blocking algorithm can use a lock queue (enqueue and dequeue with the same lock) or two locks (enqueue and dequeue with different locks) and the like to achieve, while the non-blocking implementation of the loop can be used CAS way to achieve, ConcurrentLinkedQueue is using non-blocking way to achieve thread-safe queue

BlockingQueue

todo: BlockingQueue

todo: talk concurrent (seven) - Java blocking queue

Blocking queue (BlockingQueue) is a support for two additional operations queue. These two additional operations are: the queue is empty, obtain the thread elements will wait for the queue to become non-empty. When the queue is full, the thread will wait queue storage elements available. (Ie production and consumption )

Blocking queue commonly used in the producers and consumers of the scene , the producer is added to the queue thread elements, the consumer is to take elements from the queue thread. Blocking queue storage container element is the producers, and consumers only take elements from the container.

7 provides a blocking queue. They are

  • ArrayBlockingQueue: a structure consisting of an array bounded blocking queue.
  • LinkedBlockingQueue: a linked list of structures bounded blocking queue.
  • PriorityBlockingQueue: a support prioritization of unbounded blocking queue.
  • DelayQueue: Use a priority queue unbounded blocking queue implementation.
    • Queue using PriorityQueue to achieve. Queue element must implement the interface Delayed
    • It can be used for:
      • Design caching system: You can use DelayQueue save validity cache elements, use a thread loop query DelayQueue, once DelayQueue acquired from the elements, represent a valid cached.
      • Timing task scheduling. Use task execution time DelayQueue save the day and will be executed once to obtain from DelayQueue the task started from such TimerQueue is to use DelayQueue implemented.
  • SynchronousQueue: a blocking queue element is not stored.
  • LinkedTransferQueue: a list structure consisting of unbounded blocking queue.
  • LinkedBlockingDeque: a linked list structure consisting of two-way blocking queue.

The principle of blocking queue

Using the notification mode to achieve. The so-called notification mode, that is, when the producers to full queue will block live Producer elements are added, when consumer spending elements of a queue, the queue will inform producers currently available. That use await, signal to achieve

todo: talk concurrent (seven) - Java blocking queue

reference

  1. Copy-On-Write talk container of concurrent -Java

Guess you like

Origin www.cnblogs.com/cheaptalk/p/12549668.html