Monday, May 16, 2011

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


This type of runtime errors occur due to potential deadlock situations.
I bet you might have faced it a lot if you copy codes from famous J2ME tutorial sites.(even i did)
These occurs when you do critical operations such as networking video,audio or image capture etc. inside commandAction.
The best solution for it is to just ad the trouble creating code to a new thread.
Let me show how.Let us take a sample code:-

import xyz;

class sample extends MIDlet implements CommandListener
{
 Command  start; = new Command("Start", Command.OK, 1);

 public Midlet()
 {
  start = new Command("Start", Command.EXIT, 1);
 }
 public void commandAction(Command command, Displayable displayable)
 {
  if (command == start)
  {
      potential deadlock statements
      potential deadlock statements
      potential deadlock statements
  }
 }
}

Here simply make the following changes:-


import xyz;


class sample extends MIDlet implements CommandListener,Runnable

{
Command  start; = new Command("Start", Command.OK, 1);


public Midlet()
{
start = new Command("Start", Command.EXIT, 1);

}
public void commandAction(Command command, Displayable displayable)
{
if (command == start)
{
     Thread t=new Thread(this);
     t.start();
 }

}
   public void run()
   {
       potential deadlock statements
      potential deadlock statements
      potential deadlock statements
    }


}

This will surely solve your problem

2 comments:

  1. Thanks for this post!!

    I tries like this, when i did continous http connection in while loop, its always askin permission to access internet? how can i avoid this? I know that it will not come in real device? how can i avoid in emulator? am using sun wtk.

    thanks

    ReplyDelete
  2. where have you used while loop
    It should not be done for connection.
    While loop is for iterating the read process and not the connection making process

    ReplyDelete

customised by Vaibhav