Class: UniCache::LruEviction

Inherits:
Object
  • Object
show all
Defined in:
lib/unicache.rb

Overview

LeastRecentlyUsed eviction policy. Mutex should be used to ensure atomicity of operations.

Eviction policy class should include methods:

update

Called when key is accessed (get/put).

remove

Called when key is removed.

nextEvict

Peek to what is going to be removed next.

clear

Reset eviction state.

Instance Method Summary collapse

Constructor Details

#initializeLruEviction

Instantiate.



307
308
309
310
# File 'lib/unicache.rb', line 307

def initialize
    @lock = Mutex.new
    clear
end

Instance Method Details

#clearObject

Clear eviction list.



314
315
316
317
318
# File 'lib/unicache.rb', line 314

def clear
    @lock.lock
    @list = []
    @lock.unlock
end

#nextEvictObject

Return the oldest i.e. next to be evicted.



361
362
363
# File 'lib/unicache.rb', line 361

def nextEvict
    @list[0]
end

#remove(key = nil) ⇒ Object

Remove oldest entry.

Parameters:

  • key (Object) (defaults to: nil)

    If given, remove this entry instead of oldest.



342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
# File 'lib/unicache.rb', line 342

def remove( key = nil )
    @lock.lock

    res = nil

    if key
        @list.delete_if do |i| i == key end
        res = key
    else
        res = @list.shift
    end

    @lock.unlock

    res
end

#update(key) ⇒ Object

Keep track of the least recently used keys. Place oldest at the beginning of the list.

Parameters:

  • key (Object)


325
326
327
328
329
330
331
332
333
334
335
336
# File 'lib/unicache.rb', line 325

def update( key )

    @lock.lock

    # Delete old entries of this key.
    @list.delete_if do |i| i == key end
    
    # Add to end of LRU.
    @list.push key

    @lock.unlock
end