- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to make a collection thread safe in java?
The Collections class of java.util package methods that exclusively work on collections these methods provide various additional operations which involves polymorphic algorithms.
This class provides different variants of the synchronizedCollection() method as shown below −
Sr.No | Methods & Description |
---|---|
1 | static <T> Collection<T> synchronizedCollection(Collection<T> c) This method accepts any collection object and, returns a synchronized (thread-safe) collection backed by the specified collection. |
2 | static <T> List<T> synchronizedList(List<T> list) This method accepts an object of the List interfacereturns a synchronized (thread-safe) list backed by the specified list. |
3 | static <K,V> Map<K,V> synchronizedMap(Map<K,V> m) This method accepts an object of the Map interface and, returns a synchronized (thread-safe) map backed by the specified map. |
4 | static <T> Set<T> synchronizedSet(Set<T> s) This method accepts an object of Set interface and, returns a synchronized (thread-safe) set backed by the specified set. |
5 | static <K,V> SortedMap<K,V> synchronizedSortedMap(SortedMap<K,V> m) This method accepts an object of the Map interface and, returns a synchronized (thread-safe) sorted map backed by the specified sorted map. |
6 | static <T> SortedSet<T> synchronizedSortedSet(SortedSet<T> s) This method accepts an object of the synchronizedSortedSet interface and, returns a synchronized (thread-safe) sorted set backed by the specified sorted set. |
Example
import java.util.Collection; import java.util.Collections; import java.util.Vector; public class CollectionReadOnly { public static void main(String[] args) { //Instantiating an ArrayList object Vector<String> vector = new Vector<String>(); vector.add("JavaFx"); vector.add("Java"); vector.add("WebGL"); vector.add("OpenCV"); System.out.println(vector); Collection<String> synchronizedVector = Collections.synchronizedCollection(vector); System.out.println("Synchronized "+synchronizedVector); synchronizedVector.add("CoffeeScript"); } }
Output
[JavaFx, Java, WebGL, OpenCV] Synchronized [JavaFx, Java, WebGL, OpenCV]
Advertisements