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

Version on this page:
Stackage Nightly 2019-02-18:
Latest on Hackage:

See all snapshots ttl-hashtables appears in

BSD-3-Clause licensed by Erick Gonzalez
Maintained by

Module documentation for


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


Changelog for ttl-hashtables

Unreleased changes

comments powered byDisqus