Java Concurrent Programming-3

Source: Internet
Author: User

Synchronization container prior to JDK 1.5

Before the JDK 1.5 , the main include:

    • Synchronizing containers ( Vector and Hashtable )
    • Synchronous wrapper class ( Collections.synchronizedXxx )

The common feature of these classes is that public methods are all synchronized decorated to limit the ability of only one thread to access the container at a time.

Issues that occur in the synchronization container compound operation

The old container itself does not support compound operations, including:

    1. Iterate (gets the element repeatedly until the last element in the container is obtained)
    2. Navigation (navigation, looking for the next element in a certain order)
    3. Conditional operation (Check-then-act)

Fortunately, the old container class follows a synchronization policy that supports client-side locking . To solve the problem of composite operations:

    • To resolve iterations and navigation:

      synchronized(list) { // 确保调用 size() 后, list 大小不会改变    for (int i = 0; i < list.size(); ++i) {        doSomething(list[i]);    }}
    • To resolve a condition operation:

      synchronized(list) { // 确保调用 size() 后, list 大小不会改变    int lastIndex = list.size() - 1;    list.remove(lastIndex);}

The disadvantages of doing this are:

Do anything to lock the entire container, inefficient, error prone.

Iterators andConcurrentModificationException

CollectionThe standard way to iterate is to use Iterator , either explicitly or through the syntax after the JDK 1.5 for-each .

At the time of iteration , there is still the possibility of other threads modifying the container concurrently, and using iterators will inevitably require the container to be locked during the iteration.

When an iterator is modified concurrently, the policy is in a timely failure (Fail-fast) : When the iterator is found to be modified (for example: add and remove ), an unchecked is thrown ConcurrentModificationException .

As an ArrayList example, AbstractList there is a counter inside the parent class that has a field name modCount . Any change List in the size of the operation will need to change modCount this value.

This value will be used to check for changes to the container in the iteration or, as follows:

When modified:

    if (modCount != expectedModCount)         throw new ConcurrentModificationException();    }    // Add or Remove    // .......    expectedModCount = modCount;

Iteration:

    public E prev/next() {        if (modCount != expectedModCount)             throw new ConcurrentModificationException();        }        // Other.....    }

Note: ConcurrentModificationException You can also have single-threaded code, such as when you call a method during an iteration remove

Hidden iterators

Sometimes, some operations implicitly call iterators, such as:

  1. Call toString() method, especially when writing log , there is

    log("Set:" + set);

    Such a statement.

  2. hashCodeand methods equals , the following are HashTable the hashCode and equals methods:

    Public synchronized Boolean equals (Object o) {if (o = = this) return true; if (! (    o instanceof Map)) return false;    map<?,? > t = (map<?,? >) o;    if (t.size () = size ()) return false;        try {iterator<map.entry<k,v>> i = EntrySet (). Iterator ();            while (I.hasnext ()) {map.entry<k,v> E = I.next ();            K key = E.getkey ();            V value = E.getvalue (); if (value = = null) {if (!) (            T.get (key) ==null && T.containskey (key)) return false;            } else {if (!value.equals (T.get (key))) return false;    }}} catch (ClassCastException unused) {return false;    } catch (NullPointerException unused) {return false; } return true;    public synchronized int hashcode () {int h = 0;  if (count = = 0 | | Loadfactor < 0) return h; Returns zero loadfactor =-loadfactor; Mark hashcode computation in progress entry<?,? >[] tab = table;            For (entry<?,? > Entry:tab) {while (Entry! = null) {H + = Entry.hashcode ();        Entry = Entry.next;  }} loadfactor =-loadfactor; Mark hashcode computation complete return h;}
  3. In addition containAll , removeAll iterations are retainAll generated as well.

Containers after JDK 1.5

After the JDK 1.5 , the new additions are:

    • ConcurrentHashMap, to replace synchronous Map implementations, additions put-if-absent , replacements, and conditional deletions
    • CopyOnWriteArrayList, is List the corresponding synchronous implementation
    • Queue, which is used to temporarily save a series of elements awaiting further processing, including
      • ConcurrentLinkedQueue, a traditional FIFO queue
      • PriorityQueue, a queue with a (non-concurrent) right-priority order
    • BlockingQueue, expanded from Queue , increased blocking insert and get operations.
      • If the queue is empty, then the fetch operation is blocked until an element exists;
      • If the queue is full, the insert operation is blocked until an element is removed.

After the JDK 1.6 , the newly added

    1. Dequeand BlockingDeque , respectively, expanded Queue and BlockingQueue :

      • Dequeinterface, implementation class Yes ArrayDeque , no blocking
      • BlockingDequeinterface, the implementation class is LinkedBlockingDeque , blocking.
    2. ConcurrentSkipListMapand ConcurrentSkipListSet , as SortedMap SortedSet a concurrent substitute for and

Note: Taking an element from an empty one Queue does not block, but returnsnull

ConcurrentHashMap

ConcurrentHashMapbefore, HashTable and both are SynchronizedMap synchronized by adding to the entire method synchronized , so that only one thread at a time can access the container.

ConcurrentHashMapUse a more granular locking mechanism called the detach lock . This mechanism allows for deeper shared access:

    • Any number of read threads can access the MAP concurrently.
    • The reader and the writer can access the MAP concurrently.
    • A limited number of write threads can modify the MAP concurrently.

Because of the concurrency environment, the size of the MAP is usually dynamic, size and isEmpty The return is only an estimate (which may go back and then expire).

Supported composite operations:

    1. Put-if-absent
    2. Remove-if-equal
    3. Replace-if-equal
CopyOnWriteArrayList

写入时复制(COW)The thread safety principle of the container:

As long as the non-Edge object is published correctly, access to it will not require more synchronization.

Therefore, each time an element is added/modified, a new array is created within the container, and the underlying array of the container points to the new array. The old array is still in use until it is reclaimed by GC without reference.

Because COW copy arrays have overhead, COW is suitable for container iterations that are much higher than the frequency of container modifications.

FAQ: Arrays.copyOf and the System.arraycopy difference?

Arrays.copyOfNot only will the element be copied, but a new array will also be created. System.arrayCopycopied to an existing array, the implementation is used Arrays.copyOf System.arrayCopy ;

Blocking queues and producer-consumer patterns

Producer-Consumer design separates "identifying what needs to be done" and "executing work." This mode does not find a job to be processed immediately, but instead puts the work into a task list:

    • Producers do not need to know the identity or number of consumers, or even consumers at all.
    • Consumers do not need to know who the producers are and who they are working with.
    • The relationship between producers and consumers is relative, and consumers can become producers of the next task queue

The most common producer-consumer design is the combination of a thread pool and a work queue

In the early stages of design, the use of blocking queues to establish the management of resources, early to do this is much easier than the future repair.

The Blocking queue provides a blocking put and take method. Common implementations are:

    1. LinkedBlockedQueue, FIFO, list implementation, queue First take, queue end put.
    2. ArrayBlockingQueue, FIFO, array implementation, can be inserted at Putindex (tail of queue), removed from Takeindex (queue head).
    3. PriorityBlockingQueue, taken out according to the Comparator sort order
    4. SynchronousQueue, the production line is directly connected to the consumer thread, and if the production line cannot find the consumer or vice versa, put and take will be blocked. They are always ready for the next task only when they are well-suited to the consumer.
Double-ended queues and stealing jobs

The double-ended queue is used to implement the stealing work (stealing) mode.

In traditional producer-consumer designs, all consumers share only one task queue.

In the theft of work design, each consumer has a own double-ended queue . If a consumer completes all the work in his own double-ended queue, it can steal the end of the other consumer's double-ended queue (other consumers still take the task from the queue).

Because worker threads do not compete for a shared task queue, stealing work patterns is more scalable than traditional producer-consumer designs.

Blocking and Interruptible methods

Blocking: The thread is suspended, the state BLOCKED becomes WAITING , TIMED_WAITING or waits until an event occurs before it can proceed.

BlockingQueueThe put and take method throws a checked InterruptedException , this exception indicates that this is a blocking method that can be interrupted to end the block prematurely .

Ways to handle interrupts:

    • delivery InterruptedException . Passed to the caller, which can then be thrown after a brief cleanup of the specific activity.
    • Resume interrupts . When the code is Runnable part of it, it must be captured InterruptedException . Also, call the interrupt reset interrupt state in the current thread (throwing an exception cleans up the interrupt flag bit) so that the higher-level code in the call stack can find that the interrupt has occurred.

      try {    processTask(queue.take());} catch (InterruptedException e) {    // 恢复中断状态    Thread.currentThread().interrupt();}
Synchronizer

Synchronizer is an object that adjusts the control flow of a thread according to its own state. The main types are:

    1. Signal Volume (semaphore)
    2. Level (barrier)
    3. Latching (latch)

Their characteristics: encapsulation state, which is absolutely the case when the thread executes to a certain point through or forced to wait.

Latching latch

Until the latch reaches the end state , the door is always closed, no thread can pass, and when the end state arrives, the door opens, allowing all threads to pass. Once at the end of the state, he can no longer change the state.

Case:

    1. Make sure that a calculation does not execute until it requires the initialization of the resources.
    2. Make sure that a service does not start until the other services it relies on are already started.
    3. All players wait to be ready before starting.
Futuretask

Futuretask describes the calculation of an abstract portable result. The calculation of the Futuretask is Callable achieved through.

CallableEquivalent to a portable result Runnable . Callable There are three states:

    1. Wait
    2. Run
    3. Complete (including normal end, Cancel, and exception)

To get FutureTask The result, you can call the get() method. get() when called, there are two things:

    1. If it's done, get the results directly
    2. If it is not completed, it is blocked until the task finishes returning the result or throws an exception.

FutureTaskEnsures that the calculated results are passed to the current thread safely by the calculated thread.

If an FutureTask exception is thrown on a task, the exception is encapsulated ExecutionException . The following code can remove an ExecutionException exception from:

    try {        futureTask.get();    } catch (ExecutionException e) {        Throwable cause = e.getCause();         if (cause instanceOf XXXException) {            // 自己想要捕获的异常        } else {            throw launderThrowable(cause);        }    }    public static RuntimeException launderThrowable(Throwable cause) {        if (t instanceOf RuntimeException) {            return (RuntimeException)t;        } else if (t instanceOf Error) {        } else {            throw new IllegalStateException("Not unchecked", t);        }    }
Signal Volume (Semaphore)

The count semaphore is used to control the number of activities that can access a resource at the same time, or to perform an operation at the same time.

You need to construct one before using the count semaphore, and the total number of license sets (permit) can be passed in when constructed. When using the Count semaphore, first try to obtain (acquire) a license, if there is a residual license at this time to continue to execute, if not, then block . When you're done, release a license manually (release).

Use:

    1. Constructs a fixed-length pool.
    2. Constructs a bounded blocking container.
Level (Cyclicbarrier)

Levels are used to block a set of threads until all threads reach a condition. Just like some family members designated a meeting place for the mall: "We meet each other at McDonald's 6:00, and after that, we will decide what to do next."

The difference between a level and a latch :

Levels: Waiting for other threads, which can be used repeatedly for latching: waiting for an event, can only be used once

When a thread reaches the level point, the call is await await blocked until all threads reach the level point.

    • If all threads reach the level point, the level is successfully breached and all threads are freed.
    • If the await call times out, or if the thread in the block is interrupted, the level is considered to be a failure .

      • If a thread calls a time- await out, then when the thread await times out, the thread throws an TimeoutException exception, and the other calling barrior.await() thread throws BrokenBarrierException ;

If the level is successfully passed, await a unique arrival index number is returned for each thread, which can be used to "elect" to produce a leader and take on some special work in the next iteration.

CyclicBarrierIt also allows you to pass a level behavior to the constructor (Barrier action), which is a Runnable that executes when the level is successfully passed ( in a child task thread), However, it cannot be performed until the blocking thread is freed.

Exchanger

Exchanger is another form of the level, which is a two-step level that exchanges data at the checkpoint point.

Java Concurrent Programming-3

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.