In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-21 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article is to share with you about how to analyze the implementation of Java concurrent tools in AQS. The editor thinks it is very practical, so I share it with you. I hope you can get something after reading this article.
It is well known that AQS is an underlying synchronization tool class enhanced by Java. This paper analyzes the AQS concurrent tool class from the following aspects: the resource sharing mode of AQS, the function of state, the method of customizing synchronizer, the difference between CountDownLatch,Semaphore,Semaphore and RateLimiter, and CyclicBarrier.
AQS maintains a volatile int state (for shared resources) and a FIFO thread wait queue (which is entered when multi-thread contention resources are blocked) for subsequent scheduling. In addition, there may be one or more Condition one-way linked lists for Condition processing, this one-way linked list is not necessary and may not exist.
1. Resource sharing method of AQS
Exclusive (exclusive, only one thread can execute, such as ReentrantLock)
Share (shared, multiple threads can execute at the same time, such as Semaphore/CountDownLatch)
2. The function of state
Take ReentrantLock as an example, state is initialized to 0, indicating an unlocked state. When thread A lock (), tryAcquire () is called to monopolize the lock and state+1. After that, other threads fail when they tryAcquire (), and the other threads don't have a chance to acquire the lock until the A thread unlock () to state=0 (that is, release the lock). Of course, thread A can acquire the lock repeatedly (state accumulates) before releasing the lock, which is the concept of reentrant. Note, however, that you release as many times as you get to ensure that the state returns to zero.
In CountDownLatch, for example, the task is divided into N sub-threads to execute, and the state is initialized to N (note that N should be the same as the number of threads). These N child threads are executed in parallel, and after each child thread completes execution, countDown () once, state will CAS minus 1. When all the child threads have finished executing (that is, state=0), the main thread is called by unpark (), and then the main thread is called back from the await () function to continue the subsequent action.
3. The method of customizing the synchronizer
Specific threads wait for queue maintenance (such as failed to get resources to join the queue / wake up out of the queue, etc.), AQS has been implemented at the top level. The following methods are mainly implemented when implementing a custom synchronizer:
IsHeldExclusively (): whether the thread is monopolizing resources. You need to implement it only if you use condition.
TryAcquire (int): exclusive mode. If you try to get the resource, you will return true if you succeed and false if you fail.
TryRelease (int): exclusive mode. If you try to release the resource, return true if you succeed, or false if you fail.
TryAcquireShared (int): sharing method. Try to get the resource. A negative number indicates failure; 0 indicates success, but there are no remaining resources available; a positive number indicates success and there are remaining resources.
TryReleaseShared (int): sharing method. Try to release the resource, if you are allowed to wake up the subsequent waiting node to return true, otherwise return false.
4 、 CountDownLatch
CountDownLatch is implemented through a counter whose initial value is the number of threads. Each time a thread completes its task, the value of the counter is reduced by 1. When the counter value reaches 0, it indicates that all threads have completed the task, and then the waiting thread can resume execution of the task.
Common application scenarios
Multithreading initializes resources, and the main thread pauses to wait for the initialization to finish; each thread is countDown once after initialization, and after all threads are initialized (state=0), the main thread continues to execute.
5 、 Semaphore
Semaphore can control how many resources can be accessed at the same time, obtain a license through acquire (), wait if not, and release () releases a license. The Semaphore object of a single semaphore can realize the function of mutex, and the "lock" can be acquired by one thread and released by another thread, which can be used in some situations of deadlock recovery.
Common application scenarios
Semaphore can be used for flow control, restricting access to certain resources (physical or logical), especially in application scenarios where common resources are limited, such as database connections.
6. The difference between Semaphore and RateLimiter
Semaphore: the function is to limit that only the thread that grabs the signal can execute, and everything else has to wait. You can set N signals so that up to N threads can execute simultaneously. Note that the other threads are just suspended, limiting the current by limiting the number of threads.
RateLimiter:Guava current-limiting tool class, based on token bucket algorithm. The effect is to limit that only N threads can execute in one second, and if you exceed that, you can only wait for the next second. Note that N is of type double. The current is limited in terms of speed.
7 、 CyclicBarrier
CyclicBarrier enables a certain number of threads to repeatedly assemble at the fence location. The await method is called when the thread reaches the fence position, which blocks until all threads reach the fence position. If all threads reach the fence position, the fence will open, all threads will be released, and the fence will be reset to the original count for next use.
Common application scenarios
Used for multithreading to calculate data, and finally merge the results of the scenario. Each parter is responsible for part of the calculation, and finally the data is summarized.
The above is how to analyze the implementation of Java concurrent tool class in AQS. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.