Skip to content

Instantly share code, notes, and snippets.

@vihangpatil
Created June 1, 2018 06:44
Show Gist options
  • Save vihangpatil/53b5b00355ad04aee2089aa0d022332a to your computer and use it in GitHub Desktop.
Save vihangpatil/53b5b00355ad04aee2089aa0d022332a to your computer and use it in GitHub Desktop.
Priority Queue sorted by timestamp in message. Will guarantee order for messages delayed upto 3 sec.
package io.github.vihangpatil.sandbox
import java.time.Instant
import java.util.*
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit.MILLISECONDS
import kotlin.Comparator
data class Message(
val timestamp: Long,
val name: String)
val comparator = Comparator<Message> { msg1, msg2 -> (msg1.timestamp - msg2.timestamp).toInt() }
val queue: PriorityQueue<Message> = PriorityQueue(10, comparator)
const val allowedDelay = 3 //sec
fun main(args: Array<String>) {
// images these 5 messages are received in reverse order,
// but were sent in order with 1 sec interval
val now = Instant.now().epochSecond
queue.offer(Message(now - 1L, "Five")) // 1 sec old
queue.offer(Message(now - 2L, "Four")) // 2 sec old
queue.offer(Message(now - 3L, "Three")) // 3 sec old
queue.offer(Message(now - 4L, "Two")) // 4 sec old
queue.offer(Message(now - 5L, "One")) // 5 sec old
val stse = Executors.newSingleThreadScheduledExecutor()
stse.scheduleWithFixedDelay({
if (queue.peek().timestamp < Instant.now().epochSecond - allowedDelay) {
println(queue.poll())
}
},
0, // initial delay
300, // delay
MILLISECONDS) // timeunit
// stop everything after 4 sec
stse.schedule({stse.shutdown()}, 4500, MILLISECONDS)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment