2 Replies - 303 Views - Last Post: 21 January 2013 - 04:35 PM Rate Topic: -----

#1 ClaudeP  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 9
  • Joined: 27-March 11

How can I have a thread continually process an ArrayList?

Posted 21 January 2013 - 02:25 PM

Hello! I have a thread in android that is supposed to do something with all of the elements in an arraylist until there are no more elements left, but when more elements are added do the same thing, over and over until the program is done. This is what I am doing so far:
private volatile ArrayList<StrokeQueueEntry> queue;
	public void run() {
		//Process items in the queue
		if(queue.size()>0){
			while(queue.size()>0){
                                //Lots of code here basically to process & remove the first element in the list
				Thread.yield();
			}
		}
		Thread.yield();
	}



What I am wondering is if this is the best way to do it? I am not an expert with Java or concurrency yet,

Sorry for the multipost, I pressed enter by accident and I cannot edit my post, but this is being used so the UI thread in my android app wont hang. If anyone knows a better way of doing this I would love to hear it. As far as i know the thread is doing its job and the UI thread isnt hanging, but I am not very confident if this is how I am supposed to do it?

Is This A Good Question/Topic? 0
  • +

Replies To: How can I have a thread continually process an ArrayList?

#2 ianian112  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 119
  • View blog
  • Posts: 378
  • Joined: 28-November 09

Re: How can I have a thread continually process an ArrayList?

Posted 21 January 2013 - 03:14 PM

Best way to do this would make your list a synchronized list
Collections.synchronizedList(queue), here is some documentation on it http://docs.oracle.c...java.util.List),
unfortunately to my knowledge lists in java don't give you blocking operations like queue does.

This post has been edited by ianian112: 21 January 2013 - 03:16 PM

Was This Post Helpful? 2
  • +
  • -

#3 farrell2k  Icon User is online

  • D.I.C Lover
  • member icon

Reputation: 862
  • View blog
  • Posts: 2,650
  • Joined: 29-July 11

Re: How can I have a thread continually process an ArrayList?

Posted 21 January 2013 - 04:35 PM

You should not be able to iterate over a list with one thread, while another is removing or adding elements to it. You will throw a ConcurrentModificationException.

What you want to do is utilize the observer pattern and do your other operation very time the list if modified.

This post has been edited by farrell2k: 21 January 2013 - 04:40 PM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1