Languages
[Edit]
EN

Java - iterate over synchronized ArrayList - Collections.synchronizedList(new ArrayList<>())

7 points
Created by:
Evie-Grace-Noble
621

In this article, we would like to show you how to iterate over synchronized ArrayList in thread safe way in java.

When iterating the iterator must be synchronized by programmer.

Quick solution:

Why do we need to synchronize iteration of list?

Edit
  • When we use synchronized list, probably we will share the list between multile threads.
  • Each thread will modify the list (add / get / set / remove - thread safe operations, as each operation is synchronized, read this to learn more).
  • The iterator is not synchronized and programmer needs to take care of synchronization. If we use synchronization on our list instance then, only single thread will be able to get access to the list. If it is a bit confusion for you, learn more about synchronize keyword in java.
  • Very often if we iterate a lot over synchronized list we should checkout the CopyOnWriteArrayList from (java.util.concurrent.CopyOnWriteArrayList package). We will get better performance.

Full example

Edit

 

Let's take a look at java docs of Collections.synchronizedList() method

We can take a look at implementation of SynchronizedList:

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