Java Concurrency programming

Source: Internet
Author: User
Tags closure

Built-in lock

Built-in locks are also called 同步代码块 , keywords synchronized ,

    • Lock is the object method lock, lock is this object, for class method lock, Lock is class object. So the Always object that provides the lock, if two threads request a lock at the same time, the later person will block wait until the lock is released
    • The same thread can be re-entered to acquire a lock that has already been held, so that it is not a deadlock because it is the same thread, that is, the granularity of the operation acquiring the lock is 线程 not 调用 ;
    • Reordering in the absence of synchronization, the compiler, the processor, and the runtime may make some unexpected adjustments to the execution order of the operation;
    • Minimum security reads a variable without synchronization, and may get an invalid value, but at least one of the previous threads is set, not a random value, and a non-volatile 64-bit value (double, long) does not apply. The JVM runs a 64-bit read or write operation that is decomposed into two 32-bit operations, and is not atomic;
    • Visibility for the consistency of state variables, all threads that perform read or write operations must synchronize on the same lock, otherwise the synchronization will fail;
Volatile variable

A volatile variable is a slightly weaker synchronization mechanism that is used to ensure that variables are notified to other threads of the update operation.

    • When a variable is declared as a volatile type, the compiler and the runtime will notice that the variable is shared, so the operation on that variable is not associated with other memory operations 重排序 ;
    • The volatial variable is not cached in registers or places that are not visible to other processors, so it is always the most recently written value when reading a variable;
    • It is a more lightweight synchronization mechanism than synchronized to access the volatile variable without locking and blocking the thread.
    • Do not overuse volatile, usually as a flag for an operation to complete, break out, or other state, a typical use is to check a status flag to determine whether to exit the loop
volatileboolean asleep;...    while (!asleep)        countSomeSheep();
    • Volataile only ensures visibility, such as the atomicity of the increment operation (count++) is not guaranteed;
ThreadLocal

Threadlocal provides access interfaces such as inside get and set, and maintains a separate copy of each thread that uses the variable, maintaining thread closure

    • Threadlocal saves specific and thread values in the thread object, and when the thread terminates, the values are garbage collected;
     PublicTGet() {//Optimized for the fast path.Thread CurrentThread = Thread.CurrentThread (); Values values = VALUES (CurrentThread);if(Values! =NULL) {object[] table = values.table;intIndex = 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. */    protectedTInitialValue() {return NULL; }/** * Sets the value of this variable for the current thread.     If set to * {@code null}, the value would be set to null and the underlying entry would * 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 The Values instance for this thread and variable type. */Values values (Thread current) {returnCurrent.localvalues; }
Instance closure

The data is encapsulated inside the object so that access to the data is restricted to the method of the object, from a locking that can be easier.

    • Instance closure is one of the simplest ways to build a thread-safe class, and also allows different state variables to be protected by different locks;
    • The Collections.synchronizedxxx () method is to implement thread safety by wrapping the container and locking inside the wrapper class.
Concurrent containers

JAVA5.0 provides a variety of concurrent containers to improve the performance of the synchronization container.

    • Concurrenthashmap instead of HashMap, its internal through the segmented lock, to improve the efficiency of concurrent reading and writing
    • Copyonwritearraylist, the underlying array is duplicated whenever the container is modified, so there is some overhead, so only if the iteration is much more than the modify operation, you should use the
Executor frame

Provides a standard when a method decouples a task's commit process from the execution process.
Thread pool:

    • Newfixedthreadpool creates a fixed-length thread pool, creating a thread for each task that is committed until the maximum number of threads is reached;
    • Newcachedthreadpool creates a cacheable thread pool that, when the thread pool size exceeds the processing requirements, will reclaim the idle threads, adding new threads with no limit to the size of the demand;
    • Newsinglethreadexecutor Single Thread
    • Newscheduledthreadpool creates a fixed-length thread pool, and performs tasks in a delayed or timed manner;

In order to solve the life cycle problem of service execution, executor extended the Executorservice interface and added some methods of life cycle management.

Java Concurrency programming

Related Article

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.