Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to successfully access and loop an ArrayList by multiple threads?

I need help in ArrayList. I have an arraylist of strings. I am looping through this list and sending them to the output stream one after the other. While I am looping through the list and sending them, it is possible that another thread will be adding some elements to it. After an element is sent, it must be removed from the list as well.

How can I achieve this successfully?

like image 864
kap Avatar asked May 27 '26 14:05

kap


1 Answers

If the items are added to the end of the list, you would better use a Queue instead. There are various thread-safe implementations available in Java5 and above, including ConcurrentLinkedQueue and LinkedBlockingQueue.

In general, the former is the preferable choice, unless you want a bounded blocking queue, in which case use the latter.

like image 89
Péter Török Avatar answered May 30 '26 02:05

Péter Török