multithreadingnetwork-programmingjava-memidpeclipseme

Why the J2ME Midlet Suite and HTTPConnection needs to be in different threads


I want to call a Servlet from J2ME midlet,so I've written the HTTPConnection code for the Servlet URL to call GET method.

When Midlet suites tries to connect to the Servlet URL, I've got the below message in the Emulator,

{#MyMidlet} Midlet Suite wants to connect to {#Servlet URL} using air time,
  this may result in charges, Is it ok to use airtime ?

If I click either No or Yes, nothing happened,it's just got hanged, I'm using EclipseME and SUN WTK 2.5.2. And in the console there was a warning,

Warning: To avoid potential deadlock, operations that may block, such as 
 networking, should be performed in a different thread than the 
 commandAction() handler.

Which means , If I do make the HttpConnection in a separate thread, will the problem be solved?


Solution

  • If I do make the HttpConnection in a separate thread, will the problem be solved?

    If you do it right - yes, the problem will be solved. This is a typical issue and there is standatd solution.

    Warning you refer to indicates design problem in your midlet. You have "heavyweight" activity (http connection) that runs in the same thread as UI, blocking it and making it irresponsive.

    Avoid heavy load in UI event thread. When there's much to do of something inside of commandAction or keyPressed or pointerPressed etc, just spawn a new thread to do that. To better understand why is that, consider studying this tutorial to find out how to do it right:

    Networking, User Experience, and Threads

    This article explains how your MIDlet can make network connections without compromising your user interface. It includes six iterative examples that illustrate multithreaded networking and the use of a wait screen...

    Further code examples in tutorial show how to fix design mistakes like above and how to make MIDlet user interface smoothly interoperate with networking activities.