0

I am not able to update the value of a global variable in a function which is called continuously by a thread

The function code is:

public void readMessages()
{
    if (srv.getServiceStatus() == Service.ServiceStatus.STARTED) {
        try {
            InboundMessage msg = null;
            java.util.LinkedList<InboundMessage> list = new java.util.LinkedList<InboundMessage>();
            srv.readMessages(list, InboundMessage.MessageClasses.UNREAD);

            int checkArray = list.size();

            for (int i = 0; i < list.size(); i++) {
                msg = list.get(i);
                System.out.println("New incoming message from: " + msg.getOriginator() +" : \t" + msg.getText() + "\n");
                saveSMS(msg.getOriginator(),msg.getText());

                if (checkArray == 0) {
                    messageArray = new String [4];
                    for (int j = 0 ; j<4 ; j++) {
                        messageArray[j] = "";
                    }
                }                            

                if (noOfSms < 4) {
                    messageArray[noOfSms] = msg.getText();
                    noOfSms = noOfSms + 1;
                } 
                if (noOfSms == 3) {
                    Receiver r = new Receiver ();
                    r.Processing_ReceivedSMS(msg.getText(),msg,messageArray);
                }  
            }
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }
}

Here noOfSms is the global variable but its value does not change.

The function from which readMessage is called is this:

public void run(){
    while (true){
        readMessages();

        try {
            t.sleep(5000);
            user_status=2;
        } catch (InterruptedException e) {
            System.out.println("Thread Pause Exception");
        }
    }
}

What's the reason behind it and what to do about it?

Beri
  • 11,470
  • 4
  • 35
  • 57
user1318860
  • 67
  • 1
  • 4
  • 10
  • 1
    is the variable declared as `volatile`? –  Jun 22 '12 at 12:50
  • 1
    Add some logging to the block, where you increment the `noOfSms` to see if the code is executed at all. It looks that there is a lot of conditions (`list` not empty, value less than `4`, etc..`) that have to be fulfilled in order to increase the value. – npe Jun 22 '12 at 13:07
  • @alegen no it is not and i did check it through debugging the value does not changes !! – user1318860 Jun 22 '12 at 14:36

1 Answers1

0

Since you invoke this method from thread/s there are two reasons why your variable does not get updated.

  1. the code inside readMessages() might throw any Exception before your variable gets updated
  2. there is a possibility that your variable never updates because it is located inside if blocks. Check the initial value of it so it can pass the if-condition
Nick
  • 744
  • 6
  • 11