Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Examples of Using Collections Methods | Synchronized Collections
Multithreading in Java
course content

Зміст курсу

Multithreading in Java

Multithreading in Java

1. Multithreading Basics
2. Synchronized Collections
3. High-level Synchronization Mechanisms
4. Multithreading Best Practices

bookExamples of Using Collections Methods

Note

Today we will mainly look at methods that help to create thread-safe collections.

Collections Methods

Here are some important methods provided by the class to create synchronized Collections collections:

synchronizedList(List<T> list): Returns a synchronized (thread-safe) list that supports the same contract as the passed list.

java

Main

copy
1
List<Object> listSync = Collections.synchronizedList(new ArrayList<>());

synchronizedSet(Set<T> set): Returns a synchronized (thread-safe) set that supports the same contract as the passed set.

java

Main

copy
1
Set<Object> setSync = Collections.synchronizedSet(new HashSet<>());

synchronizedMap(Map<K, V> m): Returns a synchronized (thread-safe) map that supports the same contract as the passed map.

java

Main

copy
1
Map<Object, Object> mapSync = Collections.synchronizedMap(new HashMap<>());

unmodifiableList(List<? extends T> list): Returns an immutable list containing the same elements as the specified list.

java

Main

copy
123456789101112131415
package com.example; import java.util.Collections; import java.util.List; import java.util.ArrayList; public class Main { public static void main(String[] args) { List<Integer> unmodifiableList = Collections.unmodifiableList(new ArrayList<>(List.of(1,2,3))); System.out.println(unmodifiableList); // output [1,2,3] unmodifiableList.add(4); // throw exception `UnsupportedOperationException` } }

unmodifiableMap(Map<? extends K, ? extends V> m): Returns an immutable map containing the same mappings as the specified map.

java

Main

copy
12345678910111213
package com.example; import java.util.Collections; import java.util.Map; import java.util.HashMap; public class Main { public static void main(String[] args) { Map<Integer, Integer> unmodifiableMap = Collections.unmodifiableMap(new HashMap<>()); unmodifiableMap.put(1, 2); // exception `UnsupportedOperationException` } }

unmodifiableSet(Set<? extends T> set): Returns an immodifiable set containing the same elements as the specified set.

java

Main

copy
12345678910111213
package com.example; import java.util.Collections; import java.util.Set; import java.util.HashSet; public class Main { public static void main(String[] args) { Set<Integer> unmodifiableSet = Collections.unmodifiableSet(new HashSet<>()); unmodifiableSet.add(4); // exception `UnsupportedOperationException` } }

What then is the difference between creating synchronized collections through normal implementations (those discussed in the previous chapters) and using Collections methods?

Let's look at the difference using one Map collection as an example

Differences between using ConcurrentHashMap and synchronizedMap()

ConcurrentHashMap employs an advanced method known as lock splitting, which divides the map into segments and synchronizes operations only at the segment level. This approach enables multiple threads to simultaneously read and write data across different segments of the map, improving concurrency and performance.

The method synchronizedMap() wraps the original map into a synchronized proxy object. All methods of this proxy object are synchronized, ensuring thread-safety. However, this approach can reduce performance in a multithreaded environment due to the high locking frequency involved.

For example, if ConcurrentHashMap writes to different buckets, the threads will not block each other. However, if one bucket is accessed by 2 threads, one of them will wait. On the other hand, if the collection is created via synchronizedMap(), only 1 thread will have access to all buckets, and the entire map is blocked.

This means that until one thread finishes its work, other threads will not be able to enter. As a result, operations in ConcurrentHashMap are simply executed faster.

Also in Collections there are Other Methods for Convenient Work with Collections:

Note

The Collections class provides convenient methods for working with collections in Java, simplifying commonly used operations. Synchronized collections created via Collections methods are useful for thread safety, but for more complex multithreaded tasks, it is better to use collections from the java.util.concurrent package.

1. Which method in the Collections class is used to create an immutable list?
2. Which of the following methods in the `Collections` class returns a **thread-safe** map?
3. What is the difference between ConcurrentHashMap and synchronizedMap?
Which method in the Collections class is used to create an immutable list?

Which method in the Collections class is used to create an immutable list?

Виберіть правильну відповідь

Which of the following methods in the `Collections` class returns a **thread-safe** map?

Which of the following methods in the Collections class returns a thread-safe map?

Виберіть правильну відповідь

What is the difference between ConcurrentHashMap and synchronizedMap?

What is the difference between ConcurrentHashMap and synchronizedMap?

Виберіть правильну відповідь

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 2. Розділ 8
some-alt