Restricting interface traffic in Java can be achieved through the guava class of ratelimiter or the semaphore class that comes with the JDK, a bit similar, but there are differences, to be used according to the actual situation. In simple terms,
The Ratelimiter class is to control access to interfaces at a certain rate.
The semaphore class is the amount of control that allows simultaneous concurrent access to the interface.
First, Ratelimiter class
Ratelimiter is a rate limiter that uses an algorithm called a token bucket that can be executed when the thread gets the token in the bucket. Control the rate by setting the number of tokens generated per second. Examples of use are as follows:
1 Public classTestratelimiterImplementsRunnable {2 3 Public Static FinalSimpleDateFormat SDF =NewSimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");4 5 Public Static FinalRatelimiter limiter = ratelimiter.create (1);//allows up to 1 tasks per second6 7 Public Static voidMain (string[] arg) {8 for(inti = 0; I < 10; i++) {9Limiter.acquire ();//request tokens, exceeding the license will be blockedTenThread T =NewThread (NewTestratelimiter ()); One T.start (); A } - } - the Public voidrun () { -System.out.println (Sdf.format (NewDate ()) + "Task End ..."); - } -}
Second, Semaphore class
Semaphore translation over is the semaphore, by setting the total number of semaphores, when the thread gets the semaphore, it can be executed, when the implementation is complete and then release the semaphore. This controls the number of concurrent interfaces. Examples of use are as follows:
1 Public classTestsemaphoreImplementsRunnable {2 3 Public Static FinalSimpleDateFormat SDF =NewSimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");4 5 Public Static FinalSemaphore Semaphore =NewSemaphore (5,true);//allow concurrent task volume limit to 56 7 Public Static voidMain (string[] arg) {8 for(inti = 0; I < 10; i++) {9Thread T =NewThread (NewTestsemaphore ());Ten T.start (); One } A } - - Public voidrun () { the Try { -Semaphore.acquire ();//get the semaphore, not enough will block -System.out.println (Sdf.format (NewDate ()) + "Task Start ..."); -Thread.Sleep (5000); +System.out.println (Sdf.format (NewDate ()) + "Task End ..."); -}Catch(interruptedexception e) { + e.printstacktrace (); A}finally { atSemaphore.release ();//release Semaphore - } - } -}
The second parameter in initialization true represents the principle of obtaining a semaphore in a fair way, i.e. FIFO.
Methods of restricting interface traffic in Java