Singleton in Gosu

326 views
Skip to first unread message

Jeffrey Backes

unread,
Dec 12, 2016, 6:19:03 PM12/12/16
to gosu-lang
Is this a (the) correct way to implement a thread safe singleton in gosu?

uses java.util.concurrent.locks.ReentrantLock

class Factors {

  private static var _lock = new ReentrantLock()
private static var _instance: Factors;

private construct() {
}

static property get Instance(): Factors {
if (_instance == null) {
using (_lock) {
if (_instance == null) {
_instance = new Factors()
...
}
}
}
}
}

return _instance
}

Justin Sampson

unread,
Dec 12, 2016, 6:31:24 PM12/12/16
to gosu...@googlegroups.com

Hi Jeff,

 

That's only going to be correct if _instance is volatile, which isn't (yet) supported in Gosu. Better to avoid hand-coding the double-checked locking logic altogether.

 

The first option should always be to initialize the singleton eagerly. Only bother making it lazy if it's really expensive to construct.

 

If you do really want to make it lazy, my favorite tool in Java is Suppliers.memoize() in Google's Guava libarary. You should be able to use it in Gosu like _instance = Suppliers.memoize(\ -> new Factors()) if you have Guava in your classpath.

 

If you don't want to depend on Guava, consider LockingLazyVar in Gosu's own standard library, but be sure to always provide an explicit lock in the constructor because otherwise it uses a global lock, which could cause scalability issues.

 

Cheers,

Justin

--
You received this message because you are subscribed to the Google Groups "gosu-lang" group.
To unsubscribe from this group and stop receiving emails from it, send an email to gosu-lang+...@googlegroups.com.
To post to this group, send email to gosu...@googlegroups.com.
Visit this group at https://groups.google.com/group/gosu-lang.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages