ttl-hashtables

Extends hashtables so that entries added can be expired after a TTL

Version on this page:1.3.1.0
LTS Haskell 19.33:1.4.1.0@rev:1
Stackage Nightly 2022-03-17:1.4.1.0@rev:1
Latest on Hackage:1.4.1.0@rev:1

See all snapshots ttl-hashtables appears in

BSD-3-Clause licensed by Erick Gonzalez
Maintained by [email protected]
This version can be pinned in stack with:ttl-hashtables-1.3.1.0@sha256:d8bc226cba56b2d6141e6b7e66f893730f5568e222c9ebe597c31d784f47cb9f,1995

Module documentation for 1.3.1.0

  • Data
    • Data.TTLHashTable

ttl-hashtables

This library extends fast mutable hashtables so that entries added can be expired after a given TTL (time to live). This TTL can be specified as a default property of the table or on a per entry basis.

How to use this module:

Import one of the hash table modules from the hashtables package.. i.e. Basic, Cuckoo, etc and “wrap” them in a TTLHashTable:

import Data.HashTable.ST.Basic as Basic
type HashTable k v = TTLHashTable Basic.HashTable k v

foo :: IO (HashTable Int Int)
foo = do
    -- create a hash table with maximum 2 entries and a default TTL of
    -- 100 mS
    ht <- H.newWithSettings def { H.maxSize = 2, H.defaultTTL = 100 }
    runMaybeT $ do
      H.insert ht 1 1
      H.insert ht 2 2
      H.insert ht 3 3 -- will never get past this point since max size is 2
    return ht

main :: IO ()
main = do
  ht <- foo
  v0 <- H.find ht 1
  threadDelay 200000 -- wait 200mS
  v1 <- H.find ht 2
  v2 <- H.find ht 3
  putStrLn $ "V0=" ++ show v0 -- v0 should be found
  putStrLn $ "V1=" ++ show v1 -- v1 won't be found (expired)
  putStrLn $ "V2=" ++ show v2 -- v2 won't be found (never got inserted)
  return ()

You can then use the functions in this module with this hashtable type. Note that the functions in this module which can fail offer a flexible error handling strategy by virtue of working in the context of a ‘Failable’ monad. So for example, if the function is used directly in the IO monad and a failure occurs it would then result in an exception being thrown. However if the context supports the possibiliy of failure like a MaybeT or ExceptT transformer, it would then instead return something like IO Nothing or Left NotFound respectively (depending on the actual failure of course).

None of the functions in this module are thread safe, just as the underlying mutable hash tables in the ST monad aren’t as well. If concurrent threads need to operate on the same table, you need to provide external means of synchronization to guarantee exclusive access to the table

Changes

Changelog for ttl-hashtables

Unreleased changes