Count semaphores in Java (counting Semaphore)

Source: Internet
Author: User

The semaphore (Semaphore), also known as Semaphore, is a semaphore that provides a signal in an integer variable to ensure that, in a parallel computing environment, different processes do not conflict when accessing shared resources. is a method that does not require the use of busy waiting (busy waiting).

The concept of semaphores, invented by Dutch computer scientist Edsger Dijkstra (Edsger W. Dijkstra), is widely used in different operating systems. In the system, each process is given a semaphore, which represents the current state of each process, and the uncontrolled process is forced to stop at a specific place, waiting for a signal to continue to come. If the semaphore is an arbitrary integer, it is commonly referred to as the Count Semaphore (counting semaphore), or general semaphore, if the semaphore is only binary 0 or 1, which is called binary semaphore (binary semaphore). In the Linux system, binary semaphores (binary semaphore) are also known as mutexes.

A count semaphore is implemented in Java to control the number of simultaneous accesses to a particular resource, or to perform a specified number of operations at the same time. The count semaphore can also be used to implement a resource pool, or to impose boundaries on the container.

The class that implements the count semaphore in Java is Java.util.concurrent.Semaphore, which is introduced in 1.5. A set of licenses is managed in the semaphore, and the initial number of licenses can be specified by constructing the method. You need to obtain a license (acquire) when you perform the operation, and release the license after you have finished using it. If there is currently no license, then the acquire will be blocked down until the license is available, or until it is interrupted, or the operation times out.

How to use

This can be used as follows:

Package Com.mikan.thread;import java.util.concurrent.semaphore;/** * @author Mikan * @date 2015-08-29 18:40 */public clas s semaphoretest {    private Semaphore Semaphore;    public semaphoretest (int permits) {        if (permits <= 0) {            throw new IllegalArgumentException ("Permits must is GRE Ater than 0 ");        }        semaphore = new semaphore (permits);    }    public void operation () throws Interruptedexception {        semaphore.acquire ();        try {            //do something ...        }        finally {            semaphore.release ();}}    }
The implementation of Semaphore is based on the Java.util.concurrent.locks.AbstractQueuedSynchronizer (AQS) base class, and many of the synchronization classes in the JDK are implemented based on it, such as Reentrantlock, Countdownlatch, Reentrantreadwritelock and so on. The implementation of Semaphore uses the state of Aqs to preserve the number of licenses, which implements both fair and non-equitable policies, which by default are non-equity policies that specify a fair policy when creating semaphore. When the license is 1 o'clock, it can be used as a mutex.

using semaphore to implement a bounded container

For example, use semaphore to implement a list with a specified capacity:

Package Com.mikan.thread;import Java.util.collections;import Java.util.linkedlist;import java.util.List;import java.util.concurrent.semaphore;/** * @author Mikan * @date 2015-08-29 19:11 */public class Boundedlist<t> {Priva    Te final list<t> List;    Private final Semaphore Semaphore;        public boundedlist (int bound) {list = Collections.synchronizedlist (new linkedlist<t> ());    semaphore = new semaphore (bound);        } public boolean Add (T obj) throws interruptedexception {Semaphore.acquire ();        Boolean addedflag = false;        try {addedflag = List.add (obj);            } finally {if (!addedflag) {semaphore.release ();    }} return Addedflag;        } public boolean remove (Object obj) {Boolean removedflag = List.remove (obj);        if (Removedflag) {semaphore.release ();    } return Removedflag; }//Other operations delegate to the underlying list, here is only a method public TGet (int index) {return list.get (index); }//Other methods ...}

use semaphores to control the number of concurrently executing threads
Package Com.mikan.thread;import java.util.concurrent.countdownlatch;import java.util.concurrent.semaphore;/** * @        Author Mikan * @date 2015-08-29 19:47 */public class Boundedthreadexecution {public static void main (string[] args) {        Final Semaphore Semaphore = new Semaphore (5);        Final Countdownlatch gate = new Countdownlatch (1);        int maxthreads = 100;            for (int i = 0; i < MaxThreads; i++) {final int index = i;                        New Thread (New Runnable () {@Override public void run () {try {                        Gate.await ();                        Semaphore.acquire (); System.out.println (Thread.CurrentThread (). GetName () + "--" + index + "--available permits=" +                    Semaphore.availablepermits ());                        } catch (Interruptedexception e) {e.printstacktrace ();                    Thread.CurrentThread (). interrupt ();          }          finally {//release the License Semaphore.release (), regardless of whether the current thread ends normally;        }}). Start ();    }//Use latching to implement all threads at the same time to start executing gate.countdown (); }}

Implement a count Semaphore yourself

Package com.mikan.thread;/** * @author Mikan * @date 2015-08-29 19:19 */public class Countingsemaphore {    private final int bound;    private int permits = 0;    public Countingsemaphore (int permits) {        if (permits <= 0) {            throw new IllegalArgumentException ("permits must b E greater than 0 ");        }        This.bound = permits;    }    Public synchronized Void acquired () throws Interruptedexception {        //When the license reaches the upper limit, it blocks while        (permits = = bound) {
   wait ();        }        permits++;    }    Public synchronized void release () {        permits--;        Released the license, notifies the waiting thread        notifyall ();}    }

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Count semaphores in Java (counting Semaphore)

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.