Last active
          September 15, 2018 05:16 
        
      - 
      
- 
        Save Tea-Ayataka/139aea45e0ffd84549ddd339691aec49 to your computer and use it in GitHub Desktop. 
    Kotlin Simple Rate Limiter
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | class RateLimiter(private val period: Long, private val rate: Int) { | |
| private val times = LinkedList<Long>() | |
| fun check(): Boolean { | |
| synchronized(times) { | |
| val currentTime = System.currentTimeMillis() | |
| times.removeIf { it < currentTime - period } | |
| val isLimited = times.size >= rate | |
| if (!isLimited) { | |
| times.add(currentTime) | |
| } | |
| return isLimited | |
| } | |
| } | |
| } | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment