As title states I have problem with thread based structure. What I need to do is:
-
one thread running in loop and checking if there exists something in list and if so then performing some operation on object and then removing it from list
-
function which is called from ‘outside’ and adding new objects to this list.
here is my approach:
public class Queue implements Runnable {
private List<X> listOfObjects = new ArrayList<X>;
public void addToList(X toAdd){
listOfObject.add(toAdd);
}
public void run() {
while(true){
synchronized(listOfObjects){
if(!listOfObjects.isEmpty()){
listOfObjects.get(0).doSth();
listOfObjects.remove(0);
}
}
}
}
}
Is it proper approach? Should I also synchronize adding to this list?
Looks like you should try an implementation of java.util.concurrent.BlockingQueue, rather than try and write your own! I suspect a LinkedBlockingQueue will work nicely for you. You can write entries into the queue from multiple sources, and your consumer thread will take each entry off and process it in turn, in a thread-safe fashion.
Note that your consumer thread for a
BlockingQueuewill wait (by calling thetake()method). Your implementation above, however, will spin and consume CPU whilst waiting for entries to be processed in the queue (this should be evident if you run it and monitor your CPU usage).Here’s an explanatory article.