In blackberry you cannot perform a blocking operation from the UI event thread (like SMS activity, Network operations).
You’ll need to handle these operations in a different thread otherwise you will get runtime exception blocking operation not permitted on event dispatch thread.
One more problem is there in blackberry. Single UI application cannot start more than 16 thread and total applications on blackberry device cannot start more than 128 threads if you do that, you will get TooManyThreads exception.
One solution for both problems is
int threadCount = Thread.getActiveCount();
If threadCount is 16 don’t start another thread.But this is also not a good solution.
Best solution for both problems is use single thread for all blocking operations.
1. At the app startup time start this TaskWorker thread.
public class TaskWorker implements Runnable {
private boolean quit = false;
private Vector queue = new Vector();
public TaskWorker() {
new Thread(this).start();
}
private Task getNext() {
Task task = null;
if (!queue.isEmpty()) {
task = (Task) queue.firstElement();
}
return task;
}
public void run() {
while (!quit) {
Task task = getNext();
if (task != null) {
task.doTask();
queue.removeElement(task);
} else {// task is null and only reason will be that vector has no more tasks
synchronized (queue) {
try {
queue.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public void addTask(Task task) {
synchronized (queue) {
if (!quit) {
queue.addElement(task);
queue.notify();
}
}
}
public void quit() {
synchronized (queue) {
quit = true;
queue.notify();
}
}
}
2. create a abstract Task class
public abstract class Task {
abstract void doTask();
}
3. now create tasks.
public class LoginTask extends Task{
void doTask() {
//do something
}
}
public class DownloadImageTask extends Task{
void doTask() {
//do something
}
}
4. And add these tasks to the taskworker thread
TaskWorker taskWorker = new TaskWorker(); taskWorker.addTask(new LoginTask()); taskWorker.addTask(new DownloadImageTask());
This implementation is a clean implementation of thread management not only for blackberry for j2me also.
Read the next part of the story.