In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-21 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "how to achieve flow control in high concurrency scenarios with Java Semaphore". In daily operation, I believe many people have doubts about how to achieve flow control in high concurrency scenarios with Java Semaphore. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts about "how to achieve flow control in high concurrency scenarios with Java Semaphore". Next, please follow the editor to study!
Semaphore introduction
First let's take a look at how the constructor of the Semaphore class is implemented.
Public Semaphore (int permits, boolean fair) {sync = fair? New FairSync (permits): new NonfairSync (permits);}
We can see that there are two parameters, which correspond to the number of times the semaphore is allowed and whether it is a fair lock. The concept of lock can be supplemented by reference.
Let's take a look at the main method used, tryAcquire, try to apply for a lock, and see how many implementations this method has.
Public boolean tryAcquire () {return sync.nonfairTryAcquireShared (1) > = 0;} public boolean tryAcquire (long timeout, TimeUnit unit) throws InterruptedException {return sync.tryAcquireSharedNanos (1, unit.toNanos (timeout));} public boolean tryAcquire (int permits) {if (permits)
< 0) throw new IllegalArgumentException(); return sync.nonfairTryAcquireShared(permits) >= 0;} public boolean tryAcquire (int permits, long timeout, TimeUnit unit) throws InterruptedException {if (permits)
< 0) throw new IllegalArgumentException(); return sync.tryAcquireSharedNanos(permits, unit.toNanos(timeout)); } 我们需要注意的是,Semaphore是一个可重入的共享锁,所以除了可以增加申请锁的超时时间外,还可以设置申请的许可证数量。一般在业务场景中申请1次就可以了。 Semaphore还提供了阻塞的申请方式,一旦执行就会一直阻塞直到申请到锁,就是acquire方法。有兴趣的话,可以看看,也基本上支持多种参数实现。 代码演示 下面看一下我写的demo代码,演示一下Semaphore的限流效果。 先添加一些maven依赖 cn.hutool hutool-all 5.7.15 org.projectlombok lombok true 示例代码 package com.huyi.csdn.tools; import cn.hutool.core.thread.ThreadUtil;import lombok.Builder;import lombok.Data;import lombok.extern.slf4j.Slf4j;import org.springframework.scheduling.concurrent.CustomizableThreadFactory; import java.util.Random;import java.util.concurrent.*;import java.util.concurrent.atomic.AtomicInteger;import java.util.stream.IntStream; /** * @Program: csdn @ClassName: SemaphoreDemo @Author: 剑客阿良_ALiang @Date: 2021-12-18 * 10:03 @Description: @Version: V1.0 */@Slf4jpublic class SemaphoreDemo { private static final Semaphore SEMAPHORE = new Semaphore(3, true); private static final ExecutorService POOL = Executors.newFixedThreadPool(10, new CustomizableThreadFactory("TASK-")); private static final ScheduledExecutorService ENGINE_POOL = Executors.newSingleThreadScheduledExecutor(new CustomizableThreadFactory("ENGINE-")); public static LinkedBlockingQueue taskQueue; public static AtomicInteger codeBuilder; @Data @Builder public static class Task { private Integer code; private Runnable work; } public static void init() { taskQueue = new LinkedBlockingQueue(); codeBuilder = new AtomicInteger(0); log.info(">> > Task queue initialization "); log.info (" > Task engine start "); engineOn ();} private static void engineOn () {ENGINE_POOL.scheduleAtFixedRate (()-> {if (taskQueue.isEmpty () {log.info (" queue is empty and no tasks need to be executed ") } else {if (SEMAPHORE.tryAcquire ()) {try {Task task = taskQueue.poll (); log.info ("code: {} task is licensed", task.getCode ()); POOL.submit (task.getWork ()) Log.info ("code: {} task submission for execution", task.getCode ());} catch (Exception exception) {exception.printStackTrace ();}} else {log.info ("the number of tasks executed has reached the limit and cannot be executed") }, 0,1, TimeUnit.SECONDS);} public static void addTask (Runnable runnable) {Integer code = codeBuilder.incrementAndGet () Task task = Task.builder () .code (code) .work (()-> {try {runnable.run ();} catch (Exception exception) {exception.printStackTrace ()) } finally {log.info ("code: {}-end task", code); SEMAPHORE.release ();}}) .build (); taskQueue.add (task);} public static void main (String [] args) {SemaphoreDemo.init (); Random random = new Random () For (int I = 0; I
< 10; i++) { SemaphoreDemo.addTask( () ->Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.