0

I'm new to Java and Android so bear with me.

I have one arrayList of strings that i am filling on the main UI.

I have another thread that is sending one by one the strings of the arrayList through a socket, and after sending each one it erases it from the list.

So basically it's a FIFO , with two different threads accessing the same arrayList.

How can I make this reading and writing on the same list, thread safe? Because I read that I have to, thus preventing future errors.

My first thought was creating a synchronized method to access the arrayList.

This is the method I created to access the ArrayList by both threads.

public synchronized String accessArrayList(boolean add, boolean get, String utt)
{
    if(add){            
        mStrings.add(utt);
        return null;
    }
    else if(get){
        return mStrings.get(0);

    }
    else{
        mStringsUttComm.remove(0);
        return null;
    }


}

The main thread just add's strings to this list.

The second thread does this :

Runnable runner = new Runnable() {
      public void run() {
          while(!mString.isEmpty()){
                              //socket sends string               
              sc.actionPerformed(accessArrayList(false, true, null));
                              //erase from list
              accessArrayList(false, false, null);
          }

      }
};

Is this correct? Because I am new to eclipse and I can't find a way to confirm that one thread doesn't call accessArrayList if the other one is using it.

Thank you for your time.

1 Answer 1

1

Take a look at vectors and synchronization :

Vectors : http://download.oracle.com/javase/1.4.2/docs/api/java/util/Vector.html

Synchronization : http://download.oracle.com/javase/tutorial/essential/concurrency/sync.html

Sign up to request clarification or add additional context in comments.

7 Comments

+1 ya @cornelyus use vector while using in thread and for normal method use arraylist.
Thank you.. Wasn't aware of the class Vector, will take a look. Tested again what I had done, and it seems working.. With Vector there would be no need for creating the synchronized method I did, correct?
Vectors are synchronized so you are correct whatever you do with its content, the synchronization is taking care of for you.
CopyOnWriteArrayList is thread safe but you are not guaranteed that the result you get back is up to date. That's a big factor to take into consideration but might not bother you depending on what the list is for.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.