Skip to content

Instantly share code, notes, and snippets.

@semenodm
Created February 4, 2016 22:52
Show Gist options
  • Save semenodm/a4618af5cccafa7785b6 to your computer and use it in GitHub Desktop.
Save semenodm/a4618af5cccafa7785b6 to your computer and use it in GitHub Desktop.
package org.sdo.alg.other
import java.util.concurrent.atomic.AtomicReference
/**
* Created by dsemenov
* Date: 1/28/16.
*/
class Throttler(tps: Int) {
val maxInterval = tps / 1000
val lastMessageTimeStamp = new AtomicReference[Long](-1L)
def acquire(onj: Any) = {
val lastTimestamp = lastMessageTimeStamp.get()
val currentMessageTime: Long = System.currentTimeMillis()
if (lastTimestamp == -1) {
lastMessageTimeStamp.compareAndSet(lastTimestamp, currentMessageTime)
} else {
if (currentMessageTime - lastTimestamp > maxInterval) {
lastMessageTimeStamp.compareAndSet(lastTimestamp, currentMessageTime)
} else {
false
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment