Close

Java Collections - Collections.synchronizedList() Examples

Java Collections Java Java API 


Class:

java.util.Collections

java.lang.Objectjava.lang.Objectjava.util.Collectionsjava.util.CollectionsLogicBig

Method:

public static <T> List<T> synchronizedList(List<T> list)

Returns a synchronized (thread-safe) list backed by the specified list.


Examples


package com.logicbig.example.collections;

import java.util.ArrayList;
import java.util.Collections;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class SynchronizedListExample {

public static void main(String... args) throws InterruptedException {
ArrayList<Integer> list = new ArrayList<>();
Collections.addAll(list, new Integer[10000]);
System.out.println("initial size: " + list.size());

final ExecutorService e = Executors.newFixedThreadPool(10);
int size = list.size();
for (int i = 0; i < size; i++) {
e.execute(() -> list.remove(0));
}
e.shutdown();
e.awaitTermination(1000, TimeUnit.SECONDS);
System.out.println(list.size());//should be zero
}
}

Output

initial size: 10000
164




Using synchronizedList

package com.logicbig.example.collections;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class SynchronizedListExample2 {

public static void main(String... args) throws InterruptedException {
List<Integer> integers = new ArrayList<>();
List<Integer> list = Collections.synchronizedList(integers);
Collections.addAll(list, new Integer[10000]);
System.out.println("initial size: " + list.size());

final ExecutorService e = Executors.newFixedThreadPool(10);
int size = list.size();
for (int i = 0; i < size; i++) {
e.execute(() -> {
list.remove(0);
});
}
e.shutdown();
e.awaitTermination(1000, TimeUnit.SECONDS);
System.out.println(list.size());//should be zero
}
}

Output

initial size: 10000
0




See Also