Last active
February 13, 2018 22:14
-
-
Save JohnMurray/a993e39ec9bb8a4c2f32eba1fd48c374 to your computer and use it in GitHub Desktop.
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
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