Tag Archives: restore

Saving and restoring Singletons

The Singleton pattern is one of my most favorite patterns. I use it for writing services, as controller in MVC and sometimes as settings storage.
Here’s the code how to create a Singleton in Java:

public class Singleton {
   public static Singleton instance = new Singleton();

   public static Singleton getInstance() {
      return instance;

   private Singleton() {

Sometimes you want or have to restore a Singleton and this is where it can get problematic. You could try to expose the internal state of the Singleton via a Memento but this will generally cause big troubles.

Since the idea behind the Singleton is that it only exists once and shows only one state to all classes, it does not make sense to give anyone the possibility to save and restore it.

But what if you want to keep the state of a Singleton over multiple sessions?
The best way is to load the old state when the Singleton is created. This means this will happen only once, usually the first time the Singleton is accessed. Simply build a private load function in your singleton that you call in the constructor. Inside the load function you can then read data from a file, database, de serialize an object etc. and set all private properties you need to the old state.

Now, we have a Singleton that can load it’s old state, but how do we save it?
We add a public function save to the Singleton. Every time that function is called, we save the current state of the Singleton so that we can read it later again. There is just one thing you must not forget: Thread safety.
In java, you can do this quite easy:

public void load() {
   synchronized(this) {
      // write data to the database etc

This will block any access to the object until the critical section is done.

However there is still a big question: When to save?
Unfortunately, this depends heavily on the application. You could either save whenever someone sets something (only do this when this does not happen often), schedule it (this might still cause a loss of data) or simply call it manually whenever you think the time is right.
I usually do it manually since the other options do not appeal to me. I usually only save once, when I shut down the Application, right before the exit command.

Did this help? Then please consider donating.
I do not need nor want money instead buy me some music so I can have fun while writing another guide! CDs (Amazon)
Alternatively, I am also totally into books. Books (Amazon)

Switch to our mobile site