Java Concurrency - do not understand the principle of the multi suffer

I. Introduction

Concurrent Programming in Java as compared to other learning knowledge points higher threshold, leading to a lot of people stay away. However, implementation of the system, whether in the workplace interview, or high concurrency / high traffic, but all can not do without concurrent programming, concurrent programming can then be truly master who has become the urgent needs of the job market.

Second, learn concurrent programming

Java concurrent programming Java technology stack as a mainstay of their learning cost is quite large, it was a lot of people to learn and do not know, I feel unable to start? Concurrent programming then learn whether there are some tricks in it that?

In fact, in order to allow developers freed from Java Concurrency Oliver, the great God Doug Lea purposely do a thing for Java developers that provides a Java and contracting (JUC) in the JDK, the package provides a common concurrent related tools, such as locks, concurrent cohort safety, the safety of the concurrent list, the thread pool, thread synchronization and so on. With JUC package, when writing concurrent program developers, not so difficult, but the tool is good, but if you do not know its principles, it is easy to make mistakes, that is, do not understand the principle of multi suffer.

For example, the simplest queue LinkedBlockingQueue concurrent security, the difference between their offer and put methods, when to use offer, when to use put, at some point you might know, but after a while you might forget, but if you its principle is understood, look at the code, you can know the offer is non-blocking, the queue is full, discard the current element; put is blocked, the queue is full will wait suspends the current thread.

For example, when using a thread pool, intended to allow the calling thread returns directly after the task into the thread pool, to make asynchronous task execution. If you did not pay attention if the policy is to refuse CallerRunsPolicy, and do not know the thread pool queue is full, refused to implement the policy of the current calling thread, and you deny policy which made a very time-consuming operation, the current calling thread will be blocked long time.

For example, when you use Executors.newFixedThreadPool and so create a thread pool time, if you do not know the inside it is to create an unbounded queue, then when a large number of tasks to be delivered to the thread pool created inside, might cause OOM. In addition, when you do not know which thread pool thread is a user thread or threads deamon time, and there is no method calls the shutdown thread pool, use the thread pool is created might not be elegant exit.

Several examples listed above, are intended to illustrate Even with JUC package, in fact, there are many instances can explain, do not understand the principle of multi suffer. So why can not we take the time to study the package under JUC important component implements the principle that? Some might say that I have to see ah, but can not read ah? Each component inside knowledge involved too much. Yes, indeed achieve JUC package basics of concurrent programming to build up, so look before the realization of the principle components, we should go to learn the relevant basic concurrency and progressive approach to the study.

For example, the most basic thread underlying operating primitive primitive notify / wait series, join methods, sleep method, yeild method, interrupting the thread of understanding, and avoid the deadlock, when the user thread deamon thread, and what is false sharing How to solve? What Java memory model? What is the memory invisibility and how to avoid? What volatile memory and Synchronized semantics are used to solve the problem? What is CAS operation, which appears to solve the problem, there is a problem in itself, is what the ABA problem? What is the command reordering, how to avoid? What is an atomic operation? What is exclusive locks, shared locks, lock fair, unfair lock?

If you have mastered the basis of the above, then you can look at JUC package based on the simplest atomic operations like CAS no locks for the realization of such AtomicLong, you may wonder why one of the variable value using a volatile modification (multithreaded guarantee visibility of memory)? Then we can look JDK8 new class of atomic operations LongAdder, AtomicLong performance will be affected at very high concurrent requests, although AtomicLong but after using CAS CAS failure or through an infinite loop spin locks keep trying, under high concurrency N multiple threads at the same time to operate a variable will cause a lot of threads in the CAS fails then spin state, which greatly wasted cpu resources, reducing concurrency. Well, since AtomicLong performance due to too many threads to compete update a variable decreases, then if a variable into multiple variables, so that the same number of threads to compete for more resources then the performance problem is not solved? Yes, JDK8 provided LongAdder is this idea. Here we might see themselves, that was it. You can then look simpler concurrent security CopyOnWriteArrayList based implementation of copy-on-write, as well as weak consistency of implementation principle explore the iterator (that is, copy-on-write), although its implementation which used an exclusive lock, but you can first no further details of the lock.

If you have mastered the content above, then the following core areas just as it is simply the JUC lock bag in research, you definitely want to start a first class LockSupport thoroughly studied, which is locked in a thread to suspend and wake-up infrastructure . Since the lock is based on the AQS (AbstractQueuedSynchronizer) to achieve, so you definitely want to put AQS figure it out, you will find AQS maintain a single state information state, its value can be modified by getState, setState, compareAndSetState function; for ReentrantLock for implementation, state may be used to represent the current thread to acquire a lock reentrant frequency; ReentrantReadWriteLock for a corresponding write lock state represents the upper 16 bits is read state the read lock acquisition times, to obtain the low 16 bits write lock thread reentrant times; for semaphore is used to represent the current state of the number of available signal; FutuerTask for it, the task state is used to indicate the status (e.g., has not yet begun, running, completed, canceled); corresponding to CountDownlatch and CyclicBarrie is used to represent the current state of the value of the counter.

You know AQS has internal ConditionObject class is used in conjunction with locks for thread synchronization, ConditionObject direct access to the inside of the AQS variable objects, such as state and AQS queue state value; ConditionObject conditional variables, each corresponds to a condition variable condition queue (unidirectional queue list), used to store call await condition variables () method of the thread after blocking.

You will know AQS class does not provide a usable tryAcquire and tryRelease, as AQS is the basis of the frame lock blocking and synchronizer, tryAcquire and tryRelease need for specific subclasses to achieve. Subclasses to attempt to modify the status value of the state to use CAS algorithm for the scene in time to achieve tryAcquire and tryRelease Returns true if successful, whether those returns false. Also you need to define a subclass of increase or decrease in call to acquire and release methods when the state What is the meaning of the status values.

Such as inheritance exclusive lock ReentrantLock from AQS achieved, defined as the time when the status 0 marked lock idle time is 1 marked lock has been occupied, rewriting tryAcquire time, internal usage of CAS algorithm to see the current status is zero, if use CAS to 0 to 1, and set the holder of the current thread is the current thread, and returns true, if the CAS fails it returns false.

Such as inheritance exclusive lock from AQS implemented to achieve tryRelease when the internal usage of CAS algorithm to modify the current status value from 1 to 0, and set the current lock holder is null, then return true, false if it fails if the cas.

AQS know what stuff, and then look at the lock, then certainly the easiest exclusive lock ReentrantLock, you can draw its first class view of the structure to see which variables and methods that they have, you will find that its partial lock and exclusive fair after the lock of the points (reviewed Basics?), class state values ​​representative of state of FIG thread acquires the lock of the reentrant times, when a first thread to acquire the lock state when a value of 0, the second thread acquires the lock state is 1, the number of which is reentrant. Then make it more difficult to see is how to read and write lock ReentrantReadWriteLock play, of course, do not forget StampedLock new JDK.

And other finishes, lock, so you can study the concurrent queue, the queue to which the sub-CAS-based non-blocking queue ConcurrentLinkedQueue and other lock-based blocking queue, natural look relatively simple ArrayBlockingQueue, LinkedBlockingQueue, ConcurrentLinkedQueue, do not forget High priority queue and a delay queue DelayQueue the PriorityBlockingQueue.

No, I was missing a chunk, the thread pool that? , The thread pool is mainly to solve two problems: on the one hand when a large number of asynchronous task execution when the thread pool to provide better performance, when not in use thread pool, whenever you need to perform asynchronous tasks directly when a new thread running and the thread is the need to create and destroy overhead. When using the thread pool, thread pool thread which is reusable, not asynchronous tasks when they are re-creating and destroying threads each execution. On the other hand the thread pool provides a means to limit and manage resources, such as threads can limit the number of dynamic new threads, etc., each ThreadPoolExecutor also retained some basic statistics, such as the current number of thread pool to complete the task Wait.

This is over? No foregoing explained a Java thread pool ThreadPoolExecutor inquiry principle, is part ThreadPoolExecutor Executors tools which function to introduce the following additional function is implemented ScheduledThreadPoolExecutor part, which can specify a time or after a certain delay timing task scheduling thread pools.

And so on, there is practice? Of course there must be, although Java concurrent programming content is very broad, but there are some rules to follow, such as thread, the thread pool to create time to specify a name for troubleshooting, remember to close the thread pool after use, ThreadLocal remember to call remove after use to clean up, SimpleDateFormat is not thread-safe, and so on.

If you are interested in the contents of the above, and to learn concurrent can not start, then the opportunity came, "Java Concurrency in beauty" This book is written in accordance with this idea, and the book is listed as 10 large fine on Jingdong one option books, links such as https://ranking.m.jd.com/rankInfo/share?type=rankInfo&client=apple&clientVersion=7.2.3&contentId=172548805&detailPageType=2&utm_source=iosapp&utm_medium=appshare&utm_campaign=t_335139774&utm_term=CopyURL&ad_od=share&ShareTm=Xk514t2XyZDcOWAXn4Mld%2B6NezzmBLo84DzXLJNYhzjBXOxdzqhU / Zrwj4oWzKCJkl / Bwsi6FEZ5fdL2QuG% 2B2EYyseJ5hUPUHJ1J3QXFQDimGNyYkiaAuMNprL9dWzdk0ACRD4gIC2VY / p3mDmabUH6YdkBZzwE9 % 2BxcxSnT9di4 =

5879294-5bde15b33caa154b.png
image.png

So the book is finished JUC package? No, in fact, Future asynchronous execution of the JUC is a characteristic, especially CompleteFuture appears that binds to NIO, simply TRW for. In addition CompleteFuture default task execution ForkJoinPool framework used commonPool thread pool, then you should understand that this book is not mentioned, but probably in September, will give you a surprise, so stay tuned.

Third, buying links

Taobao 618 Special 44.5 yuan

Reproduced in: https: //www.jianshu.com/p/385680eea169

Guess you like

Origin blog.csdn.net/weixin_34050427/article/details/91076164