There are two ways to synchronize explicitly:
- Using Collections.synchronizedList() method
- Using thread-safe variant of ArrayList: CopyOnWriteArrayList
Example 1: Collections.synchronizedList() method for Synchronizing ArrayList
In this example we are using Collections.synchronizedList() method. The important point to note here is that iterator should be in synchronized block in this type of synchronization as shown in the below example.
1 | package beginnersbook.com; |
- Output:
1
2
3
4Iterating synchronized ArrayList:
Pen
NoteBook
Ink
Method 2: Using CopyOnWriteArrayList
CopyOnWriteArrayList is a thread-safe variant of ArrayList.
1 | package beginnersbook.com; |
- Output:
1
2
3
4Displaying synchronized ArrayList Elements:
Pen
NoteBook
Ink