case class Elem(key: K, var value: V, var expires: Long)
private val BUCKETS = 10
private val store = new Array[LinkedList[Elem]](BUCKETS)
for(i <- 0 until BUCKETS) store(i) = new LinkedList[Elem]
def put(key: K, value: V, expires: Long): Unit = {
val b = bucket(key)
store(b).find(_.key == key) match {
case Some(x) => {
x.value = value
x.expires = expires
}
case None => {
store(b) = new LinkedList(Elem(key, value, expires), store(b))
}
}
}
def get(key: K): Option[V] = {
val now = System.currentTimeMillis
var result: Option[V] = None
// BUG: This doesn't handle the first element in the list being expired
var prev: LinkedList[Elem] = null
var i = store(bucket(key))
while (i.next != i) {
if (i.elem.expires < now) {
prev.next = i.next
} else if (i.elem.key == key) {
result = Some(i.elem.value)
}
prev = i
i = i.next
}
result
}
private def bucket(key: K) = key.hashCode % BUCKETS
}
Ya, there's a bug. Too busy ATM to think about the clean way to fix it.
import scala.collection.mutable.LinkedList
class ExpiringHashTable[K, V] {
}Ya, there's a bug. Too busy ATM to think about the clean way to fix it.