Concurrency Tool Class (iii) control the number of concurrent threads Semphore

Source: Internet
Author: User
Tags semaphore

Preface

?? In order to handle synchronization between threads, the JDK provides several useful concurrency tool classes in addition to the lock mechanism: Countdownlatch, Cyclicbarrier, Semphore, Exchanger, Phaser;
?? Countdownlatch, Cyclicbarrier, Semphore, Phaser These four tool classes provide a control of the concurrency process, while the Exchanger tool class provides a means of exchanging data between threads.

Introduction

?? Semaphore (semaphore) is the number of threads used to control access to a particular resource at the same time, by coordinating individual threads to ensure reasonable use of public resources. For many years, I feel that it is literally difficult to understand the meaning of semaphore, can only be compared to the traffic lights, such as XX Road to limit traffic, only allow at the same time there are 100 cars in this road exercise, the other must wait at the intersection, so the first 100 cars will see the green light, Can enter this road, the back of the car will see a red light, can not drive into XX Road, but if the first 100 vehicles have left the XX road, then allow 5 cars to drive into the road, the example said that the car is a thread, driving into the road is the thread in the execution, leaving the road indicates that the thread execution is complete, Seeing a red light indicates that the thread is blocked and cannot be executed.

Application Scenarios

?? Semaphore can be used for traffic control, especially for applications with limited public resources, such as database connections. If there is a need to read tens of thousands of files of data, because all are IO-intensive tasks, we can start dozens of threads concurrent read, but if the memory is read, but also need to store in the database, and the number of database connections only 10, At this point we have to control only 10 threads to get the database connection to save the data, otherwise the error will not get the database connection. At this time, we can use semaphore to do the flow control, the code is as follows:

 Public classsemaphoretest {Private Static Final intThread_count = -;Private StaticExecutorservice ThreadPool = executors.Newfixedthreadpool(Thread_count);Private StaticSemaphore s =NewSemaphore (Ten); Public Static void Main(string[] args) { for(inti =0; i < Thread_count; i++) {ThreadPool.Execute(NewRunnable () {@Override                 Public void Run() {Try{s.Acquire(); System. out.println("Save Data"); S.Release(); }Catch(Interruptedexception e)        {                    }                }            }); } threadPool.shutdown(); }}

?? In the code, although there are 30 threads executing, only 10 concurrent executions are allowed. The semaphore method Semaphore (int permits) accepts an integer number that represents the number of licenses available. Semaphore (10) indicates that 10 threads are allowed to obtain a license, that is, the maximum number of concurrent is 10. The use of semaphore is also simple, with the first thread using Semaphore's acquire () to obtain a license, and then call Release () to return the license. You can also use the Tryacquire () method to try to obtain a license.

Summary of Semphore methods 1. Obtaining Permission

?? The API provides a variety of ways to get locks:

    • can obtain one or more licenses;
    • provides blocking, non-blocking, time-outs to obtain a license;
    • provides a non-disruptive way to acquire locks in addition to interrupts;

public void Acquire () throws Interruptedexception
Gets a license from this semaphore, blocking the thread until a license is provided, or the thread is interrupted.
public void acquire (int permits) throws Interruptedexception
gets multiple licenses. A given number of licenses are obtained from this semaphore, the thread is blocked until these licenses are provided, or the thread has been interrupted.
public void acquireuninterruptibly ()
Gets a license from this semaphore and blocks it before a license is available. Non-disruptive.
public void acquireuninterruptibly (int permits)
gets multiple licenses. A given number of licenses are obtained from this semaphore, and threads are blocked until these licenses are available. Non-disruptive.
Public boolean tryacquire ()
obtains a license from the semaphore only if there is one available license for this semaphore at the time of invocation. Attempt to obtain a license in a non-blocking manner.
public boolean tryacquire (int permits)
obtains these licenses from this semaphore only if there is a given number of licenses in this semaphore at the time of invocation.
public boolean tryacquire (int permits, long timeout, timeunit unit) throws Interruptedexception
If all licenses are available for this semaphore within a given wait time, and the current thread is not interrupted, a given number of licenses are obtained from this semaphore. Timeout waiting for license
public boolean tryacquire (long timeout, timeunit unit) throws Interruptedexception
If there is a license available for this semaphore within a given wait time and the current thread is not interrupted, then a license is obtained from this semaphore.

2. Release of license

public void release ():
Release a license to return it to the semaphore.
public void release (int permits)
Releases a given number of licenses and returns them to the semaphore.

3, the provision of monitoring methods

public int availablepermits ()
Returns the number of licenses currently available in this semaphore
public int drainpermits ()
Get and return all licenses that are available immediately
Public final int Getqueuelength ()
Returns the estimated number of threads waiting to be fetched. This value is only an estimated number, because the number of threads may change dynamically while this method traverses the internal data structure. This method is used to monitor the system state and is not used for synchronization control.
Public Final Boolean hasqueuedthreads ()
Query whether the thread is waiting to be fetched.
public boolean Isfair ()
Returns true if the fairness of this semaphore is set to true.

Protected method:

Protected Collection
Returns a collection that contains the threads that may be waiting to be fetched. Because the actual thread set may change dynamically while this result is being constructed, the returned collection is only an estimate of the effort. The elements in the returned collection do not have a specific order.
protected void reducepermits (int reduction)
Reduces the number of available licenses based on the specified reduction amount. This method is useful in using semaphores to track those subclasses that become unavailable resources

@ Example GET, release multiple licenses
Try{Semaphore Semaphore =NewSemaphore (5);//Get a licenseSemaphore.Acquire();//One-time access to 4 licensesSemaphore.Acquire(4); System. out.println("Semaphore The remaining number of permits:"+semaphore.availablepermits());//One-time release of 5 licensesSemaphore.Release(5); System. out.println("Semaphore The remaining number of permits:"+semaphore.availablepermits());//release of 5 licensesSemaphore.Release(); Semaphore.Release(); Semaphore.Release(3); System. out.println("Semaphore The remaining number of permits:"+semaphore.availablepermits()); }Catch(Interruptedexception e) {e.Printstacktrace();

Operation Result:

Semaphore number of remaining licenses: 0
Semaphore number of remaining licenses: 5
Semaphore number of remaining licenses: 10

?? As can be seen from the running results above, parameter 5 in the new Semaphore (5) of the construction method is not the final license quantity, and the number of licenses can be increased by the release () method.


Literature:

    • The art of Java concurrent programming

Concurrency Tool Class (iii) control the number of concurrent threads Semphore

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.