Search code examples
glibvala

How to create a thread safe singleton in vala?


I want to create a thread-safe singleton instance for my vala class.

As you know, singletons may lead to threading issues if not properly implemented.


Solution

  • The recommended way is to use the GLib.Once construct:

    public class MyClass : Object {
    
        private static GLib.Once<MyClass> _instance;
         
        public static unowned MyClass instance () {
            return _instance.once (() => { return new MyClass (); });
        }
    }