Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing ThreadStatic singleton in F#

Tags:

singleton

f#

I'm learning F# and would like to implement ThreadStatic singleton. I'm using what I found in a similar question: F# How to implement Singleton Pattern (syntax)

With the following code compiler complains that The type 'MySingleton' does not have 'null' as a proper value.

type MySingleton = 
    private new () = {}
    [<ThreadStatic>] [<DefaultValue>] static val mutable private instance:MySingleton
    static member Instance =
        match MySingleton.instance with
        | null -> MySingleton.instance <- new MySingleton()
        | _ -> ()
        MySingleton.instance

How could I initialize the instance in this scenario?

like image 395
Domas Avatar asked Dec 07 '22 11:12

Domas


2 Answers

I think [<ThreadStatic>] leads to rather clunky code, especially in F#. There are ways to do this more concisely, for example, using ThreadLocal:

open System.Threading

type MySingleton private () = 
  static let instance = new ThreadLocal<_>(fun () -> MySingleton())
  static member Instance = instance.Value
like image 138
Daniel Avatar answered Dec 22 '22 09:12

Daniel


Another F#y solution would be to store instance as an option

type MySingleton = 
    private new () = {}

    [<ThreadStatic>; <DefaultValue>]
    static val mutable private instance:Option<MySingleton>

    static member Instance =
        match MySingleton.instance with
        | None -> MySingleton.instance <- Some(new MySingleton())
        | _ -> ()

        MySingleton.instance.Value
like image 33
Patrick McDonald Avatar answered Dec 22 '22 10:12

Patrick McDonald