Semaphore thread of the case

 

 

Outline


To improve the response speed of the interface can be used ThreadPoolExecutor + Runnable  or ThreadPoolExecutor concurrent calls  techniques parallel execution task. But ThreadPoolExecutor has a feature that when the core thread is insufficient to meet the request, the task will be added to the queue. By using the queue, then it may appear to explode queue or queue memory overflow problems caused.

In order to provide an interface speed of response as soon as possible, but we do not want to use the queue properties words. You can use a semaphore to do.

Semaphore Semaphore manage a set of permissions, you need to first obtain permission to perform an operation, and release the license after use. If you do not have a license, acquire method blocks until permission.

 

Examples of simple semaphores

ThreadPoolExecutor using semaphores

In ThreadPoolExecutor, we define the core thread parameters in time, for example, is defined as 10, so when using semaphores, initialization parameters are also set to 10.

Semaphore<Integer> sem= new Semaphore<>(10);

ThreadPoolExecutor, if you do not want to use the queue, it is necessary to ensure that only the core threads in the thread pool is always at work . Then when the request is too much, core thread to handle, however, when were blocking semaphore,

Ensuring that only when certain core thread after thread of execution, blocking just took it off.

 

As used herein, an example of a book to illustrate the basic JAVA programming concurrent usage of a semaphore.

public class BoundedHashSet<T> { public static void main(String[] args) throws Exception { BoundedHashSet<String> set = new BoundedHashSet<>(2); set.add("1"); set.add("2"); set.remove("2"); set.add("3"); System.out.println(JSON.toJSONString(set)); } private final Set<T> tempSet; private final Semaphore sem; public BoundedHashSet(int size) { this.tempSet = Collections.synchronizedSet(new HashSet<T>()); sem = new Semaphore(size); } public boolean add(T o) throws Exception { sem.acquire(); boolean isAdd = false; try{ isAdd = tempSet.add(o); return isAdd; } finally { if (!isAdd) { sem.release(); } } } public boolean remove(Object o) { boolean isRemoved = tempSet.remove(o); if (isRemoved) { sem.release(); } return isRemoved; } } 

Here example implements bounded blocking of HashSet. The HashSet only allows storage of two elements, if you want to save the third element, must wait until someone HashSet remove the elements out.

To apply for a license before each add, if we can apply to, the normal add elements. Not eligible, then acquire () method will always be blocked. remove operation inside, there is a release of the operating license.

 

Guess you like

Origin www.cnblogs.com/awkflf11/p/12637521.html