Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java ArrayList.add() method thread safe for purely parallel adding? [duplicate]

Consider a for-loop over a function that takes an ArrayList reference and adds an object to that ArrayList. I would now like to execute each function call in parallel.

Is the ArrayList.add() method thread safe if I don't care about the sequence the objects are added and no function reads or manipulates any ArrayList elements? So I only want to make sure that at the end of the parallel call all objects are added to the list.

like image 765
madison54 Avatar asked Dec 12 '14 11:12

madison54


People also ask

Is Add to ArrayList thread-safe?

ArrayList , on the other hand, is unsynchronized, making them, therefore, not thread safe. With that difference in mind, using synchronization will incur a performance hit. So if you don't need a thread-safe collection, use the ArrayList .

Can you add the same object twice to an ArrayList?

The ArrayList in java does not provide the checks for duplicate references to the same object. Therefore, we can insert the same object or reference to a single object as many times as we want.

Can we use ArrayList in multithreading?

We know that by default ArrayList class is not a thread-safe or non-synchronized. That means the multiple threads can access the same ArrayList object or instance simultaneously. Therefore, it cannot be used in the multi-threading environment without explicit synchronization.

Which of the following is thread-safe version of ArrayList class?

Method 2: Using CopyOnWriteArrayList It is a thread-safe variant of ArrayList.


1 Answers

No, it's not thread-safe. Wrap your list using Collections.synchronizedList(), or use explicit synchronization when accessing the list.

like image 199
JB Nizet Avatar answered Sep 27 '22 18:09

JB Nizet