Developers

Local Navigation

Home > Developers > Developers Knowledge Base

Back

How to - Create a singleton using the RuntimeStore

Last Updated: 02 February 2009
Article Number: DB-00686

Summary

This article applies to the following:

  • BlackBerry® Device Software 4.0 and later
  • BlackBerry smartphones based on Java® technology

Details

An application may require one or more singleton objects to be accessed from within the application itself or by other applications. The static variable ‘_instance’, in the sample below, is initialized to null for each process running on the system. Therefore, the getInstance() method needs to check the ‘_instance’ variable each time it is invoked.

To create a singleton using the RuntimeStore, use the following sample:

import net.rim.device.api.system.*;

class MySingleton {
   private static MySingleton _instance;
   private static final long GUID = 0xab4dd61c5d004c18L;

   // constructor
   MySingleton() {}

   public static MySingleton getInstance() {
      if (_instance == null) {
         _instance = (MySingleton)RuntimeStore.getRuntimeStore().get(GUID);
      if (_instance == null) {

         MySingleton singleton = new MySingleton();

         RuntimeStore.getRuntimeStore().put(GUID, singleton);
         _instance = singleton;
         }
      }

      return _instance;

   }
}

Use Cases

A singleton based on the above sample code might be used in the following scenarios:

  • A network manager class that handles all network-related requests for an application
  • A packet/message sender class
  • A debugging/logging class

Keywords

Singleton, RuntimeStore, IPC, interprocess communication, thread, network