Java concurrent programming

Source: Internet
Author: User

Java concurrent programming
Built-in lock

Built-in locks are also calledSynchronous Code Block, Keywordsynchronized,

The lock locks the object method. The lock is the object, locks the class method, and the lock is the class object. Therefore, the lock is always an object. If two threads request the lock at the same time, the latecomer will block and wait until the lock is released and re-entered into the same thread to obtain another lock that has already been held, it is guaranteed that a deadlock does not occur because it is the same thread, that is, the Operation granularity for obtaining the lock is ThreadInstead CallIn the absence of synchronization, the compiler, processor, and runtime may make some unexpected adjustments to the execution sequence of operations; the lowest security is to read variables without synchronization, an invalid value may be obtained, but at least it is set by a previous thread, instead of a random value. non-volatile 64-bit values (double, long) are not applicable, JVM runs 64-bit read or write operations into two 32-bit operations, which do not have atomicity. Visibility is consistent with state variables, all threads that execute read or write operations must be synchronized in the same lock; otherwise, the synchronization will fail; volatile variable

The volatile variable is a slightly weaker synchronization mechanism to ensure that the variable update operation is notified to other threads.

When the variable is declared as volatile, the compiler and runtime will notice that the variable is shared, so the operations on the variable will not be combined with other memory operations. ReorderThe volatial variable is not cached in a register or invisible to other processors, so that the latest written value is always read when the variable is read. The lock operation is not performed when the volatile variable is accessed, so there is no thread blocking, so it is a more lightweight synchronization mechanism than synchronized; do not over-use volatile, usually used as a sign that an operation is completed, interrupted, or in other states, A typical usage is to check a status sign to determine whether to exit the loop.
volatile boolean asleep;...    while (!asleep)        countSomeSheep();
Volataile only ensures visibility. For example, it cannot guarantee the atomicity of incremental operations (count ++); ThreadLocal

ThreadLocal provides access interfaces such as get and set, and stores an independent copy for each thread that uses this variable to keep the thread closed.

ThreadLocal stores the specific and Thread values in the Thread object. After the Thread is terminated, these values are recycled as garbage;
    public T get() {        // Optimized for the fast path.        Thread currentThread = Thread.currentThread();        Values values = values(currentThread);        if (values != null) {            Object[] table = values.table;            int index = hash & values.mask;            if (this.reference == table[index]) {                return (T) table[index + 1];            }        } else {            values = initializeValues(currentThread);        }        return (T) values.getAfterMiss(this);    }    /**     * Provides the initial value of this variable for the current thread.     * The default implementation returns {@code null}.     *     * @return the initial value of the variable.     */    protected T initialValue() {        return null;    }    /**     * Sets the value of this variable for the current thread. If set to     * {@code null}, the value will be set to null and the underlying entry will     * still be present.     *     * @param value the new value of the variable for the caller thread.     */    public void set(T value) {        Thread currentThread = Thread.currentThread();        Values values = values(currentThread);        if (values == null) {            values = initializeValues(currentThread);        }        values.put(this, value);    }    /**     * Gets Values instance for this thread and variable type.     */    Values values(Thread current) {        return current.localValues;    }
Instance closed

Encapsulate the data in the object, so that access to the data is limited to the object method, from which the lock can be easier.

Instance blocking is the simplest way to build thread security classes, and different state variables can be protected by different locks; Collections. the synchronizedXXX () method is to package containers and lock the internal packaging class to ensure thread security. Concurrent containers

Java provides multiple concurrent containers to Improve the Performance of synchronization containers.

Instead of HashMap, ConcurrentHashMap improves the efficiency of concurrent read/write by using segment locks. CopyOnWriteArrayList copies the underlying array whenever a container is modified, which has certain overhead, therefore, the Executor framework should be used only when iterative operations are much more than modification operations.

A standard method is provided to decouple the task submission process from the execution process.
Thread Pool:

NewFixedThreadPool creates a fixed-length thread pool. Each time a task is submitted, a thread is created until the number of threads reaches the maximum value. newCachedThreadPool creates a cache-able thread pool, when the thread pool size exceeds the processing requirement, Idle threads will be recycled. When the demand increases, new threads will be added, with unlimited size. newSingleThreadExecutor creates a fixed-length thread pool for a single thread newScheduledThreadPool, in addition, tasks are executed in a delayed or scheduled manner;

To solve the lifecycle problem of the execution service, Executor extends the ExecutorService interface and adds some lifecycle management methods.

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.