3 people like it.

Concurrent Memoization with Timeout

This is variant of http://www.fssnip.net/sA that is having a time-out. You may want to use this if you e.g. cache a database query result or other mutable data source.

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
20: 
21: 
22: 
23: 
open System
open System.Collections.Concurrent  
let cache = ConcurrentDictionary<(string * obj),Lazy<obj>>()
let cacheTimes = ConcurrentDictionary<string,DateTime>()
let memoizeConcurrent (caller:string) cacheTimeSeconds (f: ('a -> 'b)) = fun x ->
    match cacheTimes.TryGetValue caller with
    | true, time when time < DateTime.UtcNow.AddSeconds(-cacheTimeSeconds)
        -> cache.TryRemove((caller, x|>box)) |> ignore
    | _ -> ()
    (cache.GetOrAdd((caller, x|>box), 
        lazy (( cacheTimes.AddOrUpdate(caller, DateTime.UtcNow, fun _ _ ->DateTime.UtcNow) |> ignore
                f x)|>box)).Force() |> unbox) : 'b

(* Example test:
let cacheTimeSeconds = 30.
let myfun = memoizeConcurrent "myTest" cacheTimeSeconds (fun f -> Console.WriteLine("SideEffect"); f + 1)
myfun 3 // "SideEffect"
myfun 5 // "SideEffect"
myfun 3
System.Threading.Thread.Sleep ((cacheTimeSeconds |> int) * 1000 + 100)
myfun 3 // "SideEffect"
myfun 3
*)
namespace System
namespace System.Collections
namespace System.Collections.Concurrent
val cache : ConcurrentDictionary<(string * obj),Lazy<obj>>

Full name: Script.cache
Multiple items
type ConcurrentDictionary<'TKey,'TValue> =
  new : unit -> ConcurrentDictionary<'TKey, 'TValue> + 6 overloads
  member AddOrUpdate : key:'TKey * addValueFactory:Func<'TKey, 'TValue> * updateValueFactory:Func<'TKey, 'TValue, 'TValue> -> 'TValue + 1 overload
  member Clear : unit -> unit
  member ContainsKey : key:'TKey -> bool
  member Count : int
  member GetEnumerator : unit -> IEnumerator<KeyValuePair<'TKey, 'TValue>>
  member GetOrAdd : key:'TKey * valueFactory:Func<'TKey, 'TValue> -> 'TValue + 1 overload
  member IsEmpty : bool
  member Item : 'TKey -> 'TValue with get, set
  member Keys : ICollection<'TKey>
  ...

Full name: System.Collections.Concurrent.ConcurrentDictionary<_,_>

--------------------
ConcurrentDictionary() : unit
ConcurrentDictionary(collection: Collections.Generic.IEnumerable<Collections.Generic.KeyValuePair<'TKey,'TValue>>) : unit
ConcurrentDictionary(comparer: Collections.Generic.IEqualityComparer<'TKey>) : unit
ConcurrentDictionary(concurrencyLevel: int, capacity: int) : unit
ConcurrentDictionary(collection: Collections.Generic.IEnumerable<Collections.Generic.KeyValuePair<'TKey,'TValue>>, comparer: Collections.Generic.IEqualityComparer<'TKey>) : unit
ConcurrentDictionary(concurrencyLevel: int, collection: Collections.Generic.IEnumerable<Collections.Generic.KeyValuePair<'TKey,'TValue>>, comparer: Collections.Generic.IEqualityComparer<'TKey>) : unit
ConcurrentDictionary(concurrencyLevel: int, capacity: int, comparer: Collections.Generic.IEqualityComparer<'TKey>) : unit
Multiple items
val string : value:'T -> string

Full name: Microsoft.FSharp.Core.Operators.string

--------------------
type string = String

Full name: Microsoft.FSharp.Core.string
type obj = Object

Full name: Microsoft.FSharp.Core.obj
Multiple items
active recognizer Lazy: Lazy<'T> -> 'T

Full name: Microsoft.FSharp.Core.ExtraTopLevelOperators.( |Lazy| )

--------------------
type Lazy<'T> =
  new : unit -> Lazy<'T> + 5 overloads
  member IsValueCreated : bool
  member ToString : unit -> string
  member Value : 'T

Full name: System.Lazy<_>

--------------------
Lazy() : unit
Lazy(valueFactory: Func<'T>) : unit
Lazy(isThreadSafe: bool) : unit
Lazy(mode: Threading.LazyThreadSafetyMode) : unit
Lazy(valueFactory: Func<'T>, isThreadSafe: bool) : unit
Lazy(valueFactory: Func<'T>, mode: Threading.LazyThreadSafetyMode) : unit
val cacheTimes : ConcurrentDictionary<string,DateTime>

Full name: Script.cacheTimes
Multiple items
type DateTime =
  struct
    new : ticks:int64 -> DateTime + 10 overloads
    member Add : value:TimeSpan -> DateTime
    member AddDays : value:float -> DateTime
    member AddHours : value:float -> DateTime
    member AddMilliseconds : value:float -> DateTime
    member AddMinutes : value:float -> DateTime
    member AddMonths : months:int -> DateTime
    member AddSeconds : value:float -> DateTime
    member AddTicks : value:int64 -> DateTime
    member AddYears : value:int -> DateTime
    ...
  end

Full name: System.DateTime

--------------------
DateTime()
   (+0 other overloads)
DateTime(ticks: int64) : unit
   (+0 other overloads)
DateTime(ticks: int64, kind: DateTimeKind) : unit
   (+0 other overloads)
DateTime(year: int, month: int, day: int) : unit
   (+0 other overloads)
DateTime(year: int, month: int, day: int, calendar: Globalization.Calendar) : unit
   (+0 other overloads)
DateTime(year: int, month: int, day: int, hour: int, minute: int, second: int) : unit
   (+0 other overloads)
DateTime(year: int, month: int, day: int, hour: int, minute: int, second: int, kind: DateTimeKind) : unit
   (+0 other overloads)
DateTime(year: int, month: int, day: int, hour: int, minute: int, second: int, calendar: Globalization.Calendar) : unit
   (+0 other overloads)
DateTime(year: int, month: int, day: int, hour: int, minute: int, second: int, millisecond: int) : unit
   (+0 other overloads)
DateTime(year: int, month: int, day: int, hour: int, minute: int, second: int, millisecond: int, kind: DateTimeKind) : unit
   (+0 other overloads)
val memoizeConcurrent : caller:string -> cacheTimeSeconds:float -> f:('a -> 'b) -> x:'a -> 'b

Full name: Script.memoizeConcurrent
val caller : string
val cacheTimeSeconds : float
val f : ('a -> 'b)
val x : 'a
ConcurrentDictionary.TryGetValue(key: string, value: byref<DateTime>) : bool
val time : DateTime
property DateTime.UtcNow: DateTime
DateTime.AddSeconds(value: float) : DateTime
ConcurrentDictionary.TryRemove(key: string * obj, value: byref<Lazy<obj>>) : bool
val box : value:'T -> obj

Full name: Microsoft.FSharp.Core.Operators.box
val ignore : value:'T -> unit

Full name: Microsoft.FSharp.Core.Operators.ignore
ConcurrentDictionary.GetOrAdd(key: string * obj, value: Lazy<obj>) : Lazy<obj>
ConcurrentDictionary.GetOrAdd(key: string * obj, valueFactory: Func<(string * obj),Lazy<obj>>) : Lazy<obj>
ConcurrentDictionary.AddOrUpdate(key: string, addValue: DateTime, updateValueFactory: Func<string,DateTime,DateTime>) : DateTime
ConcurrentDictionary.AddOrUpdate(key: string, addValueFactory: Func<string,DateTime>, updateValueFactory: Func<string,DateTime,DateTime>) : DateTime
val unbox : value:obj -> 'T

Full name: Microsoft.FSharp.Core.Operators.unbox

More information

Link:http://fssnip.net/7Pv
Posted:4 years ago
Author:Tuomas Hietanen
Tags: cache , memoization , memoize , timeout