Java Concurrency tool Class (III) Semaphore to control the number of concurrent threads

Source: Internet
Author: User
Tags semaphore

Role

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.

Brief introduction

Semaphore is also a thread-synchronous helper class that maintains the number of threads that are currently accessing itself and provides a synchronization mechanism. You can use semaphore to control the number of threads that access resources concurrently, for example, to implement the number of concurrent accesses allowed for a file.

Summary of Main methods:

void Acquire (): Gets a license from this semaphore to block the thread before providing a license, or the thread is interrupted.

void release (): Releases a license to return it to the semaphore.

int availablepermits (): Returns the number of licenses currently available in this semaphore.

Boolean hasqueuedthreads (): Query whether the thread is waiting to be fetched.

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:

1  Public classSemaphoretest {2 3     Private Static Final intThread_count = 30;4 5     Private StaticExecutorservice ThreadPool =Executors6 . Newfixedthreadpool (thread_count);7 8     Private StaticSemaphore s =NewSemaphore (10);9 Ten      Public Static voidMain (string[] args) { One          for(inti = 0; i < Thread_count; i++) { AThreadpool.execute (NewRunnable () { - @Override -                  Public voidrun () { the                     Try { - S.acquire (); -SYSTEM.OUT.PRINTLN ("Save Data"); - s.release (); +}Catch(interruptedexception e) { -                     } +                 } A             }); at         } -  - 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.

Other methods

Semaphore also provides some other methods:

    • int availablepermits (): Returns the number of licenses currently available in this semaphore.
    • int getqueuelength (): Returns the number of threads that are waiting to acquire a license.
    • Boolean hasqueuedthreads (): Whether the thread is waiting to acquire the license.
    • void reducepermits (int reduction): reduces reduction licenses. is a protected method.
    • Collection getqueuedthreads (): Returns all thread collections waiting to acquire a license. is a protected method.

Reference: The Art of Java concurrent programming

Java Concurrency tool Class (III) Semaphore to control the number of concurrent threads

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.