Question

In my j2me JAVA app there is a Thread which initializes an object which I right after that has to get by returning it's value in other class.

In my main class where I call that Thread right after that I have to get the value that was changed in Thread, but issue comes that before completion of the thread that function is called and it returns null and program doesn't proceed further.

What I did was to put that returning value wait till a boolean status doesn't get true inside the thread but because of that while loop it hangs there and doesn't come back.

I am posting the code below let me know the best solution, remember this code is in J2me (Java) which has limited functionality even for threading so don't suggest me methods like Latch or BackgroundWorker because it doesn't work here.

Here is the Thread and other function which hsa to return the value

public synchronized void run() {
    try {
        contacts.removeAllElements();
        pim = PIM.getInstance();
        String lists[] = pim.listPIMLists(PIM.CONTACT_LIST);
        for (int i = 0; i < lists.length; i++) {
            //code for custom backup operation
            if (customCode == 1 && i == 0) {
                continue;
            } else if (customCode == 0 && i > 0) {
                continue;
            }
            clist = (ContactList) pim.openPIMList(PIM.CONTACT_LIST, PIM.READ_WRITE, lists[i]);
            Enumeration cenum = clist.items();
            while (cenum.hasMoreElements()) {
                Contact c = (Contact) cenum.nextElement();
                ContactDTO contact = new ContactDTO();
                parseContactInfo(c, contact);
                contacts.addElement(contact);
            }
            clist.close();
        }
        readComplete = true;
    } catch (Exception e) {
    }
}

//Return contacts loaded into vector list
public ContactVector getLoadedContacts() {
    while(!readComplete){
         Thread.sleep(100);
        }
     return contacts;
}

This is main class from where I have to call this

public ContactVector getContactVector() {
    DeviceContactRetriever dcr = new DeviceContactRetriever(this, language);
    dcr.start();
    ContactVector vector = dcr.getLoadedContacts();      //problem line*
    return vector;
}

so *problem line returns the object before completion and hence it's null.

Was it helpful?

Solution

Your problem is that code is not synchronized.

You need to use methods wait() and notify(), about like below:

public synchronized void run() {
    try {
        contacts.removeAllElements();
        //...
        readComplete = true;
        this.notify();
    } catch (Exception e) {
    }
}

//Return contacts loaded into vector list
public synchronized // <-- note sync'd here
        ContactVector getLoadedContacts() {
    while(!readComplete){
         this.wait();
        }
     return contacts;
}

This is pretty basic stuff, consider studying Java tutorials on concurrency.

If possible, look for tutorials for Java versions earlier than Java 5, otherwise explanation of things you can use in Java ME (limited to Java 1.3 as of now) will be "mixed" with modern features, making it harder to learn parts that are relevant for you.

An example tutorial that worked that way for me was by Jacob Jenkov here, chapters from "Introduction..." to "Slipped Conditions" inclusive. Note further chapters ("Locks" and the rest) aren't bad either but these heavily rely on features introduced since Java 5 (JSRs 133 / 166 - JMM and concurrency utilities).


Couple obsevations on the code not related to the bug explained above.

  1. Since your code is quite complicated, consider adding log messages to make it easier to debug (as explained eg here). In particular I'd strongly to log things like exception in catch block (search web for something like _Java don't swallow exceptions" if you're interested why), as well as whether lists is null and if it isn't, what is its size and whether clist, cenum and c are null or not.

  2. Consider making your code easier to read and modify by extracting into separate methods (as explained here) code that is in your snippet within for and while loops.

  3. Note that since code in getContactVector() might take a long time to run, you better avoid calling it from UI thread. If you're interested to understand why is that and how to do it right, check the tutorial "Networking, User Experience, and Threads" referred to in lcdui tag wiki.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top