Concurrency control Artifact Semaphore Java Concurrency Tool class

Source: Internet
Author: User
Tags semaphore

Semaphore (semaphore) is used to control the number of threads that are notified of access to a particular resource by coordinating individual threads to ensure reasonable use of public resources.

We can understand so semaphore, such as a toilet only 6 pits, while only to meet 6 people to the toilet (abnormal), others want to squat, only waiting in line, if someone from the toilet out, the back of a person can go in. In this example, the person is a thread, the squat pit indicates that the thread is executing, leaving indicates that the thread has finished executing, and the number of pits represents the semaphore number.

I. Application scenarios for Semaphore

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 to read concurrently, 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. This time, you can use semaphore to do flow control. The simple implementation is as follows:

  

 Public classSemaphoretest {Private Static Final intThread_count = 30; Private StaticExecutorservice ThreadPool =Executors.newfixedthreadpool (Thread_count); //only 10 database links, creating 10 semaphores here    Private StaticSemaphore Semaphore =NewSemaphore (10);  Public Static voidMain (string[] args) {BooleanShutdownthreadpool =false;  for(intindex = 0; Index < Thread_count; index++) {Threadpool.execute (NewRunnable () {@Override Public voidrun () {Try {                        //Get a signalSemaphore.acquire (); //Perform ActionsSystem.out.println ("Wait for write data ..."); Thread.Sleep (1000); //Release Signalsemaphore.release (); } Catch(interruptedexception e) {e.printstacktrace ();            }                }            }); if(Index = = thread_count-1) {Shutdownthreadpool=true; }        }         while(!Shutdownthreadpool)        {Threadpool.shutdown (); }    }}

Although 30 threads are created in the code above, there can be only one thread executing concurrently. 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. Semaphore is also very simple to use, first the thread uses the semaphore acquire () method to obtain a license, and then call the release () method to return the license. You can also use the Tryacquire () method to try to obtain a license.

Two. Other methods of semaphore

  int availablepermits (): Returns the number of licenses currently available

  int getqueuelength (): Gets the number of threads that are waiting to acquire a license

  boolean hasqueuedthreads (): Gets whether there are still threads waiting to get a license

  void reducepermits (int reduction): reduction of reduction licenses

Concurrency control Artifact Semaphore Java Concurrency Tool class

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.