Say I have a LinkedList filled objects and each objects stores relevant information that I need. I have threads accessing this list's first element to retrieve the information and do some operations on it, at the end of the operation I want that first element removed from the list. How do I make sure that remove() is only called once for each element? So that each threads can access the same next element on the list?
public class Test {
private static LinkedList<foo> list;
public static void main(String args[]) {
list = new LinkedList<>();
list.add(foo1);
list.add(foo2);
list.add(foo3);
for(int i = 0; i < 5; i++) {
new Thread(run()).start();
}
}
private static Runnable run() {
while(true) {
while(SomeCondition) {
//Do work.
}
list.remove();
}
}
}
I've tried creating a lock for the remove methods but this caused significant lag between each element for all the thread. Is it a good idea to just have a
LinkedList<LinkedList<food>> mainList;
so that each thread will have its own list to work off of? Then each thread can just do this to access the their element:
mainList.get(i).element();
mainList.get(i).remove();
EDIT: I failed to mentioned that main() has it's own thread where it continuously adds more elements into the list. The main purpose is that this is a server where it constantly receives requests, the requests are being placed in the list as a "queue". then the other threads spun off main() performs the operations. The request's message contains a field that will let me know which thread will perform what operation.
EDIT 2: I may have been too vague on the requirement to get a proper answer, sorry! This is a server that constantly receives requests from one client, The the list is being constantly populated with requests, the most important field for this purpose is the requested time:
for(int i = 0; i < 5; i++) {
new Thread(run(i)).start();
}
private static Runnable run(int streamNumber) {
while(true) {
while(SomeCondition) {
//Do work.
}
list.remove();
}
}
So then the streamNumber dictates the following: 1. What IP address I am broadcasting to. 2. Using the requested time and streamNumber, which pointer to a payload I need to use(from a file).
Finally, each thread will send the payload out. So each thread needs the same information, but will respond differently. Once it sends the payload, it will grab the next requested time and do everything all over again.