Skip to content

Instantly share code, notes, and snippets.

@JohnMurray
Last active February 13, 2018 22:14
Show Gist options
  • Save JohnMurray/a993e39ec9bb8a4c2f32eba1fd48c374 to your computer and use it in GitHub Desktop.
Save JohnMurray/a993e39ec9bb8a4c2f32eba1fd48c374 to your computer and use it in GitHub Desktop.
import java.time.LocalDateTime
import java.util.{Deque, LinkedList}
import scala.concurrent.{Future, Promise}
import scala.concurrent.duration._
class ApiService[T](limit: Long, timeFrame: FiniteDuration) {
case class RequestQueueItem(f: () => Future[T], p: Promise[T])
private var requestQueue: Deque[RequestQueueItem] = new LinkedList[RequestQueueItem]()
private var requestCount: Long = 0
private var windowStopTime: LocalDateTime = LocalDateTime.now()
def request(f: () => Future[T]): Future[T] = this.synchronized {
val p = Promise[T]()
requestQueue.offerLast(RequestQueueItem(f, p))
tryRequest()
p.future
}
private def tryRequest(): Unit = this.synchronized {
if (hasCapacity()) {
makeRequest()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment