Is ArrayList is synchronized by default or else we can make it as synchronized or not

Is ArrayList synchronized by default or else we can make it as synchronize or not?

Options
- ArrayList is synchronized by default
- ArrayList is not Synchronized we cannot make it synchronized
- ArrayList is not Synchronized but we can make it using - Collections.synchronizedList[new ArrayList[]];
- ArrayList is not Synchronized but we can make it Synchronized using - ArrayList.synchronnizedList[new ArrayLis[]];


CORRECT ANSWER : ArrayList is not Synchronized but we can make it using - Collections.synchronizedList[new ArrayList[]];
  • « Previous
  • Next »

1. Collections.synchronizedList[] to synchronize ArrayList

This method returns a synchronized thread-safe list backed by the specified list. It is recommended that we should manually synchronize on the returned list when traversing it via Iterator, Spliterator or Stream. Else it may result in non-deterministic behavior.

No explicit synchronization is needed to add, remove elements from synchronized arraylist.

List namesList = Collections.synchronizedList[new ArrayList[]]; //List methods are synchronized namesList.add["Alex"]; namesList.add["Brian"]; //Use explicit synchronization while iterating synchronized[namesList] { Iterator iterator = namesList.iterator[]; while [iterator.hasNext[]] { System.out.println[iterator.next[]]; } }

Program output.

Alex Brian

What is synchronization ArrayList?

Synchronization is about preventing concurrent access. With ArrayList [or Collections in general] there are two concurrency problems. First, there is method synchronization. This means, all calls to methods of an ArrayList instance are synchronized. So there is always only one method executed at a time.

Is ArrayList synchronized by default or we can make it as synchronized?

Is ArrayList synchronized by default or else we can make it as synchronize or not? – ArrayList is not Synchronized but we can make it using – Collections. synchronizedList[new ArrayList[]]; – ArrayList is not Synchronized but we can make it Synchronized using – ArrayList.

How do I create a synchronized collection?

Here are the detailed Steps:

  1. Create an ArrayList.
  2. Populate the arrayList with elements, with add[E e] API method of ArrayList.
  3. Invoke the synchronizedList[List list] API method of Collections to get the synchronized list from the provided ArrayList.

How to Synchronize ArrayList in Java?

We can use Collections.synchronizedList[List] method to synchronize collections in java. The synchronizedList[List] method is used to return a synchronized [thread-safe] list backed by the specified list.

Output:

Mango Banana Apple Strawberry Pineapple

Next TopicJava Collections Interview Questions


← prev next →


Video liên quan

Bài mới nhất

Chủ Đề