Common tools for concurrent Programming (II) Symaphore implementing a thread pool

Source: Internet
Author: User
Tags semaphore

1.symaPhore Introduction

Symaphore (semaphore) is used to control the number of threads that concurrently access a resource, typically in concurrent traffic control. The personal understanding of it is equivalent to the reception room can only receive a fixed number of people, when the maximum number of reception, the other people will be intercepted outside waiting, the current face out of the reception room, will continue to receive the following people.

2.symaphore use

Symaphore has two constructor methods: the constructor method semaphore (int permits) accepts an int parameter, which represents the number of available licenses, an unfair lock is created internally by default, and the constructor method semaphore (int permits, Boolean fair) accepts a

int and a boolean value that represent the number of available licenses and whether fair locks are used. (Fair lock and non-fair lock are mentioned separately later in the article)

Generally in the flow control, we can control the number of licenses to control the size of the concurrency, the next specific talk about how to achieve the control of the thread pool, the code is as follows:

1  Public classDbpoolsemaphore {2     3     Private Final Static intPool_size = 10;4     Private FinalSemaphore useful,useless;//useful represents an available database connection, useless represents a used database connection5     6      PublicDbpoolsemaphore () {7          This. useful =NewSemaphore (pool_size);8          This. Useless =NewSemaphore (0);9     }Ten      One     //containers that hold database connections A     Private StaticLinkedlist<connection> pool =NewLinkedlist<connection>(); -     //Initialize Pool -     Static { the          for(inti = 0; i < pool_size; i++) { - Pool.addlast (Sqlconnectimpl.fetchconnection ()); -         } -     } +  -     /*Return Connection*/ +      Public voidReturnconnect (Connection Connection)throwsinterruptedexception { A         if(connection!=NULL) { atSystem.out.println ("currently has" +useful.getqueuelength () + "Threads waiting for database connection!! " -+ "Number of available connections:" +useful.availablepermits ()); - Useless.acquire (); -             synchronized(pool) { - Pool.addlast (connection); -             }     in useful.release (); -         } to     } +      -     /*get connected from the pool*/ the      PublicConnection Takeconnect ()throwsinterruptedexception { * Useful.acquire (); $ Connection Conn;Panax Notoginseng         synchronized(pool) { -conn =Pool.removefirst (); the         } + useless.release (); A         returnConn; the     } +}

First, two Symaphore objects were created, respectively, to indicate that the thread pool and the available thread pool were used, respectively, to call acquire () and release () when designing the connection and returning the connection, and acquire () was used to obtain the license, release () to return the license, The equivalent is to get the connection to the available connection pool to obtain the license, get to continue execution, otherwise blocking wait until a connection pool is returned to the connection, the available thread license can be obtained, obtain a database connection, and then will not be available connection license increases; The essence is to control the effect of concurrent traffic by controlling the number of available and unavailable licenses.

Here is an example of the code I designed to execute:

1  Public classApptest {2 3     Private StaticDbpoolsemaphore Dbpool =NewDbpoolsemaphore ();4     5     //Business Threads6     Private Static classBusithreadextendsthread{7 @Override8          Public voidrun () {9Random r =NewRandom ();//let each thread hold a connection for a different timeTen             LongStart =System.currenttimemillis (); One             Try { AConnection connect =Dbpool.takeconnect (); -System.out.println ("Thread_" +Thread.CurrentThread (). GetId () -+ "_ Get Database Connection time Elapsed" "+ (System.currenttimemillis ()-start) +" "Ms."); thesleeptools.ms (100+r.nextint (100));//simulating business operations, threads holding connection query data -SYSTEM.OUT.PRINTLN ("Query data complete, return the connection!") "); - dbpool.returnconnect (connect); -}Catch(interruptedexception e) { +             } -         } +     } A      at      Public Static voidMain (string[] args) { -          for(inti = 0; I < 50; i++) { -Thread thread =NewBusithread (); - Thread.Start (); -         } -     } in      -}

Interested students can use the above code to run, you can see the first 10 threads do not consume time, can be directly obtained, the latter will be blocked (spend more and more time), returned to get a connection, because my connection license is set to 10, so the maximum number of concurrent each time is 10.

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.

PS: partially referenced from http://ifeve.com/concurrency-semaphore/

Common tools for concurrent Programming (II) Symaphore implementing a thread pool

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.