The semaphore of Java concurrent programming

Source: Internet
Author: User

I. Overview

Technical semaphores are used to control the number of activities that can access a particular resource at the same time, or to perform data for a given operation at the same time. Count semaphores can be used to implement resource pools or to limit boundaries to a container.

Semaphores maintain a license set, and the initial amount of the license is passed to the semaphore through the constructor function. The activity acquires the license and releases the license after use, and if no licenses are available, the acquire method is blocked until it is available. Each release method adds a license that may release a blocking fetch.

A degenerate form of calculating a semaphore is a two-dollar semaphore: a semaphore with an initial value of 1, and a two-dollar semaphore that can be used as a mutex.

Second, the application scenario

Semaphores can be used to implement resource pools, such as database connection pools. The sample code is as follows:

classPool {Private Static Final intmax_available = 100; Private FinalSemaphore available =NewSemaphore (Max_available,true);  PublicObject GetItem ()throwsinterruptedexception {available.acquire (); returnGetnextavailableitem (); }        Public voidPutItem (Object x) {if(markasunused (x)) available.release (); } myresource Resource1=NewMyResource ("Resource 1"); MyResource Resource2=NewMyResource ("Resource 2"); MyResource Resource3=NewMyResource ("Resource 3"); protectedmyresource[] Items =NewMyresource[]{resource1,resource2,resource3}; protected Boolean[] used =New Boolean[max_available]; protected synchronizedObject Getnextavailableitem () { for(inti = 0; i < max_available; ++i) {if(!Used[i]) {Used[i]=true; returnItems[i]; }         }         return NULL;//Not reached       }       protected synchronized Booleanmarkasunused (Object item) { for(inti = 0; i < max_available; ++i) {if(Item = =Items[i]) {              if(Used[i]) {Used[i]=false; return true; }               Else                return false; }         }         return false; }}classmyresource{String resourcename;  PublicMyResource (String resourcename) { This. resourcename=resourcename; }}
Iii. Methods of Use

constructor function:

Semaphore (int permits):创建具有给定许可数和非公平设置的Semaphore

Semaphore (int Permits,boolean Fair): This class's construction method optionally accepts a fairness parameter. When set to False, this class does not guarantee the order in which a thread acquires a license. In particular, intrusion is allowed, meaning that a thread can be assigned a license to the thread that is already waiting, acquire() logically, that the new thread will put itself in the head of the waiting thread queue. When the fairness is set to true, the semaphore guarantees that for any 获取 thread that invokes the method, the thread is selected and licensed according to the order in which they are invoked (that is, first-out, FIFO). Note that FIFO sorting is necessarily applied to the specified internal execution point within these methods. Therefore, it is possible that a thread is called before another thread acquire , but it arrives at the sorting point after the thread, and is similar when it returns from the method.

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.

The sample code is as follows:

 Public classsemaphoretest{ Public Static voidMain (string[] args) {Semaphore Semaphore=NewSemaphore (3);  for(inti=0;i<5;i++) {MyThread MyThread=NewMyThread ("Thread" +I, Semaphore);        Mythread.start (); }    }    Static classMyThreadextendsThread {String name;        Semaphore Semaphore;  PublicMyThread (String name,semaphore Semaphore) { This. name=name;  This. semaphore=Semaphore; } @Override Public voidrun () {Try{semaphore.acquire (); SYSTEM.OUT.PRINTLN (Name+ "Get the semaphore, start working ..."); Thread.Sleep (3000); SYSTEM.OUT.PRINTLN (Name+ "End of work" + "number of threads waiting to get licenses:" +semaphore.getqueuelength ()); }             Catch(interruptedexception e) {//TODO Auto-generated catch blockE.printstacktrace (); }            finally{semaphore.release (); }        }    }}

The results of the implementation are as follows:

 

Iv. references

1. Java Concurrency Programming practice

The semaphore of Java concurrent programming

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.