Welcome!

Welcome to the official BlackBerry Support Community Forums.

This is your resource to discuss support topics with your peers, and learn from each other.

inside custom component

Java Development

Create a singleton using the RuntimeStore

by Retired ‎02-12-2010 02:36 PM - edited ‎09-16-2010 03:13 PM (5,899 Views)

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
Contributors
Users Online
Currently online: 41 members 1,447 guests
Please welcome our newest community members: