Thread Safe singleton class

You are implementing the lazy initialization pattern – where the instance is created when first used. But there is a simple trick that allows you to code a threadsafe implementation that doesn’t require synchronization! It is known as the Initialization-on-demand holder idiom, and it looks like this: public class CassandraAstyanaxConnection { private CassandraAstyanaxConnection(){ } private … Read more

@staticmethod with @property

User kaizer.se was onto something as far as the original question goes. I took it a step further in terms of simplicity, so that it now requires only a single decorator: class classproperty(property): def __get__(self, cls, owner): return classmethod(self.fget).__get__(None, owner)() Usage: class Stats: _current_instance = None @classproperty def singleton(cls): if cls._current_instance is None: cls._current_instance = … Read more

Using Singleton design pattern for SQLiteDatabase

Click here to see my blog post on this subject. Here is some sample code that illustrates three possible approaches. These will allow access to the database throughout the application. Approach #1: have `SQLiteOpenHelper` be a static data member This isn’t the complete implementation, but it should give you a good idea on how to … Read more

Why is volatile used in double checked locking

A good resource for understanding why volatile is needed comes from the JCIP book. Wikipedia has a decent explanation of that material as well. The real problem is that Thread A may assign a memory space for instance before it is finished constructing instance. Thread B will see that assignment and try to use it. … Read more

What is the best approach for using an Enum as a singleton in Java?

Suppose you’re binding to something which will use the properties of any object it’s given – you can pass Elvis.INSTANCE very easily, but you can’t pass Elvis.class and expect it to find the property (unless it’s deliberately coded to find static properties of classes). Basically you only use the singleton pattern when you want an … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)