Languages
[Edit]
EN

Java - create thread safe ArrayList (Collections.synchronizedList)

7 points
Created by:
Brett4
465

In this article, we would like to show you how to create thread safe ArrayList in java.

Quick solution:

 

Full example with imports:

 

Iterating over Collections.synchronizedList

Edit

When iterating the iterator must be synched by programmer.

Let's take a look at java docs:

We can take a look at implementation of SynchronizedList:

Explanation

Edit

When we enter Collections.synchronizedList(new ArrayList<>()) method, we will see that all methods of list are wrapped by synchronized.

We can read more about lock / mutex here:

Java Collections synchronizedList implementation (java 11 corretto):

 

1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Java concurrency

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join