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

Close connections

by Retired ‎02-16-2010 11:10 AM - edited ‎09-16-2010 02:22 PM (6,494 Views)



This article applies to BlackBerry® Device Software.




There are several mechanisms available to developers to open connections to the network from a BlackBerry device. For example, developers can use the BlackBerry Mobile Data System™ (BlackBerry MDS™), provided with the BlackBerry Enterprise Server™, to connect to web servers behind the corporate firewall.


When connecting to the network, the application must properly close the connections for the following reasons:


  1. Connections that are closed improperly are not cleaned up by the garbage collector on the BlackBerry device. These connections continue to use space on the BlackBerry device and degrade the performance of the system.
  2. Connections that are closed improperly may prevent threads from completing as expected, which causes unexpected application behaviour over a long length of time (for example, TooManyThreadsError).
  3. On the BlackBerry device, the DirectTCP stack has an upper limit of five simultaneous connections. If connections are not closed properly, applications will run into the java.io.IOException: Max connections opened error. For more information, see this article.


There is a specific order expected for closing connections, as shown in the code sample below. Therefore, it is important to close the input stream, output stream, and then the connection itself. Also, these steps should be completed in a finally block to make sure that they are always executed.



HttpConnection conn = null;
OutputStream out = null;
InputStream in = null;
try {
conn = (HttpConnection)Connector.open( "http://www.foo.com" );
out = conn.openOutputStream();

// Perform operations for using output stream

in = conn.openInputStream();

// Perform operations for using input stream
} catch( IOException e ) {
// Perform operations for handling IOException
} finally {
if (in != null) {
try {
} catch (IOException e) {
if (out != null) {
try {
} catch (IOException e) {
if (conn != null) {
try {
} catch (IOException e) {




Users Online
Currently online: 4 members 2,254 guests
Please welcome our newest community members: