Java Semaphore semaphore

Source: Internet
Author: User
Tags semaphore

In many cases, there may be multiple threads that require access to a small number of resources. It is assumed that several threads are running on the server that answer client requests. These threads need to connect to the same database, but at any one time
Only a certain number of database connections can be obtained. How will you be able to effectively allocate these fixed number of database connections to a large number of threads?

A: 1. Add a synchronous lock to the method to ensure that only one person can call this method at the same time, all other threads are queued, but in this case even if you have 10 database links, there is always only one in the
Use status. This will greatly waste the system resources, and the operating efficiency of the system is very low.
2. Another approach, of course, is to use semaphores, which can greatly improve efficiency and performance by using the same number of semaphore licenses as the number of available connections in the database.

The semaphore class is a count semaphore that must be freed by the thread that gets it,
This is typically used to limit the number of threads that can access some resources (physical or logical).

One semaphore has and only 3 operations, and they are all atomic: Initialize, increase, and decrease
Increase can be unblocked for a process;
The reduction allows a process to enter the block.

Semaphores maintain a license set and, if necessary, block each thread before obtaining a license:
A given number of licenses are obtained from this semaphore, and threads are blocked until these licenses are available.
acquireuninterruptibly (int permits) {}
Each release () adds a license that may release a blocked fetch.
Semaphore only counts the number of available licenses and takes action accordingly.

How do I get Semaphore objects?
Public Semaphore (int Permits,boolean Fair)
Permits: Initialize the number of licenses available.
Fair: True if the semaphore is guaranteed to be granted in FIFO order at the time of requisition, otherwise false;

How do I get a license from the semaphore?
public void Acquire () throws Interruptedexception

How do I release a license and return the semaphore?
public void Release ()

Import Java.util.concurrent.executorservice;import Java.util.concurrent.executors;import java.util.concurrent.semaphore;/** * Application of thread semaphore Semaphore * * @author xxxxx * */public class Semaphorethread {private I    NT A = 0;        /** * Bank Savings class */class Bank {private int account = 100;        public int Getaccount () {return account;        ' public void ' Save (int money) {account + = money;        }}/** * thread execution class, save 10 dollars per time */class Newthread implements Runnable {private Bank bank;        Private Semaphore Semaphore;            Public Newthread (Bank Bank, Semaphore Semaphore) { = Bank;        This.semaphore = semaphore;            } @Override public void Run () {int b = a++;            if (semaphore.availablepermits () > 0) {System.out.println ("thread" + B + "Start, enter the bank, have the location to save money immediately");      } else {System.out.println ("thread" + B + "Start, enter bank, no position, go to queue wait");      } try {semaphore.acquire ();       (10);                System.out.println (b + "account balance:" + bank.getaccount ());                Thread.Sleep (1000);                SYSTEM.OUT.PRINTLN ("thread" + B + "Saving up, leaving the bank");            Semaphore.release ();            } catch (Interruptedexception e) {e.printstacktrace ();        }}}/** * Create thread, call internal class, start saving * * public void Usethread () {Bank Bank = new Bank ();        Define 10 semaphores Semaphore Semaphore = new Semaphore (2);        Create a cache thread pool Executorservice es = Executors.newcachedthreadpool (); Create 20 threads for (int i = 0; i < i++) {//execute a thread es.submit (new Newthread (ban        K, Semaphore));        }//Close thread pool Es.shutdown ();        Obtain two licenses from the semaphore and block the thread semaphore.acquireuninterruptibly (2) until the license is obtained;        System.out.println ("to the point, staff to eat"); Release two licenses and return them to the semaphore SEMAPhore.release (2);        } public static void Main (string[] args) {semaphorethread test = new Semaphorethread ();    Test.usethread (); }}
Semaphore is typically used to limit the number of threads that can access certain resources (physical or logical)

A preliminary study on semaphore realization Principle:
Semaphore is used to protect access to one or more shared resources, and the semaphore internally maintains a counter with a value of the number of shared resources that can be accessed. To access a shared resource, a thread obtains the semaphore first, and if the semaphore counter value is greater than 1, meaning that a shared resource can be accessed, subtract 1 from its counter value, and then access the shared resource.
If the counter value is 0, the thread enters hibernation. When a thread finishes using the shared resource, the semaphore is released and the counter inside the semaphore is incremented by 1, before the thread that enters hibernation is awakened and attempts to obtain the semaphore again.

Use of Semaphore:
Semaphore need to build a parameter to specify the number of shared resources, semaphore after the completion of the construction is to obtain semaphore, shared resources after the use of the release semaphore

Semaphore Semaphore = new Semaphore (10,true);
Semaphore.acquire (); //From this semaphore obtain a license to block a thread until a license is provided, or the thread is interrupted
Do something here
Semaphore.release ();//release a license to return it to the semaphore

Java Semaphore 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: 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.