Subscribe via RSS
Select Language

BlackBerry API Hidden Gems (Part One)

BlackBerry Development Advisor

 Gems
 
Every time I think I know everything, I am always proven wrong.  For example, I used to think I knew everything about BlackBerry® APIs but as I continue developing software I am still finding new, cool classes and methods that make my life easier.  I call them “hidden gems” since they are often found by one stumbling across them, but when found are of great use.  In this post I will highlight some of my favourite gems, which I hope will make your life as a developer easier too.  So let’s dive in. 
 

Weak References

For the longest time I had heard the term “weak references” but never really knew what they were.  Once I finally learned, I started to use them all the time to be more efficient and avoid memory leaks.  Indeed, weak references are not BlackBerry specific, but are defined right in the CLDC specification in the class java.lang.ref.WeakReference.

So what is a “weak reference” anyways?  The behaviour of a weak reference when contrasted with the normal “strong” reference pertains to making an object a candidate for garbage collection. A weak reference gives you the ability to access an object but also makes it available to the garbage collector.  So why would this be useful?  I find that there are often circumstances when you only care about an object if someone else does.  Holding a weak reference to an object is one way of determining if anyone else cares about it, based on the assumption that anyone who cares about it will hold a strong reference to it.  Once nobody cares about the object (other than me) it will be garbage collected.  This is the opposite of holding a strong reference to the object, as doing so would prevent the object from being garbage collected, wasting precious memory.

One excellent use case for weak references is holding a reference to an application object.  In general, you only need to reference an application object while the application it represents is alive; once the application exits you no longer need the reference. By holding a strong reference to the application object, the garbage collector will be prevented from freeing the object’s memory even after the application exits, along with the massive number of objects that it recursively references. Instead, holding a weak reference to the application object allows it to be garbage collected when the application exits.

Below is an example of how a weak reference to an application object can be used in a memory-efficient manner to determine if an application is still alive.
 

import net.rim.device.api.system.Application;
import java.lang.ref.WeakReference;

public class ApplicationLifeMonitor {

private WeakReference _appRef;

public ApplicationLifeMonitor() {
Application app = Application.getApplication();
_appRef = new WeakReference(app);
}

public boolean isAlive() {
Application app = (Application) _appRef.get();
return (app != null && app.isAlive());
}
}

 

UIDGenerator

The UIDGenerator class does exactly what its name implies: generates unique IDs.  Its class javadocs defines it as “a utility class to generate 32-bit unique IDs that can be used for synchronization or any other purpose.” Here’s an example to show how it could be used:

 

public class Person {

private int _id;
private String _name;

public Person(String name) {
this._id = UIDGenerator.getUID();
this._name = name;
}

public int getId() {
return this._id;
}

public String getName() {
return this._name;
}
}

 

IOUtilities.streamToBytes()

Have you ever written code like this to dump the bytes from an InputStream into a byte[] array?

public static byte[] getBytes(InputStream in)
throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[2048];
int readCount = in.read(buffer);
while (readCount >= 0) {
out.write(buffer, 0, readCount);
readCount = in.read(buffer);
}
return out.toByteArray();
}

 

Now you can do it in one line:
 

public static byte[] getBytes(InputStream in)
throws IOException {
return net.rim.device.api.io.IOUtilities.streamToBytes(in);
}

 
Impress your friends at your next partywith this neat trick. 
 
Stay tuned for tomorrow's post when I'll share even more BlackBerry API gems with you!
Message Edited by dconeybeare on 08-17-2009 10:33 AM

Comments
by Chris H-C(anon) on 08-12-2009 04:38 PM
Can the code samples be text? Having them as images seems a little silly.
by BlackBerry Development Advisor on 08-13-2009 12:58 PM
Yeah, you're right.  In today's post I put the source code in as text.  Thanks!
by on 08-16-2009 12:40 AM
Thanks, I could never figure out what is/how-to use the WeakReference.
by kylefowler on 08-17-2009 12:56 PM
Thank you, i could not figure out weakreferences either! haha
by rumplestiltskin on 08-17-2009 06:45 PM
Re. using WeakReferences to determine if your application is running.  Where would this be useful?  If the application is no longer running then wouldn't the code that calls isAlive also stop running?
by Cristian J(anon) on 08-19-2009 07:51 PM
Maybe using a WeakReference would be useful when one launches a new screen from another screen and then closes the former. That way the closed screen and all it's objects would be garbage collected. Am I right?
by BlackBerry Development Advisor on 08-20-2009 02:14 PM

In response to rumplestiltskin...

 

You are right that in general invoking Application.isAlive() to determine whether or not an application is running is a good way to do it.  When an application exits then all threads of that application are destroyed and most of the application is garbaged collected.  The example that I gave above was somewhat contrived, but would be useful if one application wanted to determine if another application was alive without preventing its Application object from being garbage collected.

 

As a more realistic example, suppose you register a PhoneListener with the net.rim.blackberry.api.phone.Phone class.  Even after your application exits the listener will be referenced and will be notified of phone events.  So if the implementation of PhoneListener holds a strong reference to the Application object then it will not be able to be garbage collected.  In this case, holding a weak reference to the Application object in the PhoneListener prevents this problem, especially since an Application object is more-or-less useless after the application it represents has exited.

 

Hope this makes sense.  Feel free to continue the discussion!

 

--Denver

by BlackBerry Development Advisor on 08-20-2009 02:21 PM

In response to Cristian J, "Maybe using a WeakReference would be useful when one launches a new screen from another screen and then closes the former. That way the closed screen and all it's objects would be garbage collected. Am I right?"

 

I'm not sure I fully understand what you mean.  When you say that a screen "launches" another screen do you mean that it pushes another screen onto the display stack using UiApplication.pushScreen()?  If so, I don't think that a weak reference would be of benefit in this case because screens do not have any implicit references to other screens on the display stack.  Once a screen is closed (a.k.a. removed from the display stack) then it and all of the objects it recursively references are available for garbage collection, assuming that no other references to those objects exist.

 

Let me know if I misunderstood your question and I'll attempt to clarify.

by rumplestiltskin on 08-26-2009 12:24 AM

If your listener implementation held a WeakReference to the app then yes your app would be able to be GCed but you still have the listener hanging around after the app terminates which is not good.  I think it would be best practice to tear down your listener when the app exits.  In conjunction with this I think it would make sense for the implementation of Phone's listener dispatcher to hold weak references to the listeners themselves.  That way the system ensures that misbehaved apps that do not deregister themselves don't stick around forever as zombie processes.  Phone is one example but there are other global listener registries in the system that I think would benefit from holding Weak references to their listeners ( LowMemoryManager for example).

 

Another prime use of weak references would be implementing a cache.

Post a Comment
Be sure to enter a unique name. You can't reuse a name that's already in use.
Be sure to enter a unique email address. You can't reuse an email address that's already in use.
Type the characters you see in the picture above.Type the words you hear.
About BlackBerry Developer's Blog
The Developer Relations team at RIM is focused upon providing solutions for all stages of the BlackBerry development lifecycle. The Developer’s Blog is a forum to share best practices, market insight and developer-engagement opportunities with the development community. The Developer’s Blog complements our existing outreach programs (BlackBerry Developer Conference and Developer Newsletter) while giving us an opportunity to share our personalities too!

About the Author
  • Adam is a product manager at RIM in the platform product management team. Adam’s focus and responsibility is on setting the strategy and direction of the BlackBerry web platform, including the web developer tooling products. He is also responsible for RIM’s involvement with the Eclipse Foundation and the Pulsar project. Adam hopes this blog will allow him to share his knowledge, viewpoint and passion for BlackBerry, but is really interested in what capabilities the community feels should be added to the web platform and tooling to create even more compelling web applications and content.
  • Adam is an Application Development Consultant with the Developer Relations Team at RIM. As a member of the Developer Relations Team, Adam manages the technical relationship with ISVs who specialize in producing applications based on web technologies. Adam's development background consists of a degree in Computer Science and work in web development for both the insurance and technical support industries.
  • I joined Research In Motion in 2005 working with Independent Software Vendors (ISVs) who specialize in Bluetooth, GPS, multimedia, and gaming. As a senior member of the Developer Relations Team it's my mandate to not only support the application development efforts for a number of ISVs, but it's also to act as a voice at RIM for third party application developers. Like RIM, my roots are in the enterprise world, but over the past couple of years I've quickly adapted to the consumer space, and that's where I spend most of my time today.
  • Chris has been at RIM since 2001 and runs R&D for the BlackBerry Development Platform. Practically speaking, this means day-to-day he is busy harnassing the innovative power of a talented group of RIM engineers to serve the needs of the BlackBerry Developer community.
  • Denver is a software developer at RIM, working on the BlackBerry Java APIs. Denver has been working at RIM for 4 years and started in automated testing of the APIs, making the switch to development in 2008. He enjoys programming, and finds developing for BlackBerry especially interesting. Denver also enjoys writing and sharing his development experiences, and hopes his posts will be useful and informative to other developers out there.
  • With more than a half-decade of experience in the wireless industry, Douglas “tr0n” Soltys has chronicled the evolution of mobile culture in both the consumer and enterprise space. Prior to joining RIM, Douglas manned the helm of wireless weblogs QuicklyBored and BlackBerry Cool. When not blogging about all things BlackBerry®, Douglas can be found extolling the virtues of Strunk and White. He uses a BlackBerry® Bold™.
  • As Manager, Developer Programs at Research In Motion (RIM), Ian and his team are responsible for the design and delivery of programs and services for BlackBerry developers – including support tools and resources, recognition, advocacy, go-to-market, and regional programs. Ian is passionate about making sure that BlackBerry developers have everything they need in order to be successful from the inception of an idea to app deployment or commercialization. Prior to joining Developer Relations, Ian was a Product Manager for various BlackBerry solutions including the BlackBerry Java Development Environment, BlackBerry Maps, and BlackBerry Mobile Voice System.
  • Kamen is a Senior Architect, Strategic Initiatives, and started at RIM in 2001 with already established expertise in development for the BlackBerry platform and other mobile devices. Since then Kamen has been part of both device and server-side design and development activities - helping to evolve the BlackBerry development environment. As part of the Strategic Initiatives group he is now involved in looking for new ways to bring additional value to third party developers.
  • Mike Kirkup is the Director for the Developer Relations program at Research In Motion (RIM), which is responsible for managing the technical relationships and programs for RIM’s developer community worldwide. Mike and his team work with RIM’s developer community to provide support and guidance as developers work to integrate their applications to the BlackBerry platform. Mike joined RIM in 2001 as a Security Software Developer in RIM’s Wireless Security Group. As part of the Wireless Securty group, Mike contributed to the development of the BlackBerry Cryptography API, S/MIME and PGP implementations. Mike holds a Masters of Management Science and a Bachelor of Mathematics from the University of Waterloo.
  • When he’s not out riding the waves off the sunny eastern coast of Australia, you’re likely to find Neil at his desk answering emails, taking calls, or cutting code in his role of Application Developer Consultant for RIM. As a member of the Developer Relations team Neil spends a great deal of time working with Independent Software Vendors (ISVs) in Australia and New Zealand helping them get the most out of the BlackBerry platform, and also working behind the scenes to ensure everything is “most excellent” for all developers. Neil’s been developing for the BlackBerry for five years and prior to joining RIM ran a successful BlackBerry software company. He also likes hats.
  • Prosanta is a member of the BlackBerry Developer Relations team specializing in Web Development. Prosanta’s focus is on developing out the web platform and tools associated with web development while supporting the development efforts of a number of Independent Software Vendors. Prior to joining RIM, Prosanta had worked on numerous web portals for major multinational firms writing both front and backend code.
  • Tim is the Development Manager for BlackBerry development tooling. This includes Java, Web and also Theme creation tools. He is always hanging out in the development forums trying to help out where he can and to bring your feedback into the next releases of BlackBerry tooling. You’ll also see Tim presenting various topics at the BlackBerry Developer Conference and Wireless Enterprise Symposium so be sure to stop by and say hi. Just don’t start talking about cars or Batman or you won’t be able to get rid of him.
  • I work on the Developer Relations team at RIM, with a focus on enterprise applications for Sales Force Automation, Health Care, Public Safety and Real Estate. I started on the team at the beginning of 2007.
Categories