Which Java collections are synchronized (thread safe) and which are not?

Which Java collections are synchronized and which are not?

Example: HashSet is out of sync

+16
source share
10 answers

There are three groups of collections.

  • The Java 1.0 collection, which is mainly related to obsolete classes. This includes Hashtable, Vector, Stack. They are synchronized, but I do not recommend using them. Properties is perhaps the one exception, but I would not use it in a multi-threaded context.
  • The Java 1.2 collections added in 1998, which largely replace this collection, are not synchronized, but can be synchronized using the Collections.synchronizedXxx() methods
  • Java 5.0 concurrency updates, added in 2004, support locks, thread safe collections.

In short, none of the collections that I would recommend you use are synchronized.

+10
source

You can get a synchronized version of Java Collection with

 Collections.synchronizedCollection(Collection<T> c) 

[ javadoc ]

+7
source

The simple answer: no Collection implementation is synchronized, because synchronized not a property of the class, it applies only to methods and blocks.

I suppose you want to know which implementations are thread-oriented, which classes from the java collection infrastructure can be safely used in a multi-threaded environment.

Information is always included in javadoc ( as here: Arraylist - which is not thread safe)

+7
source

Thread Safe Collections -

  1. Concurrenthashmap

Thread safe without synchronizing the entire card. Very fast read when recording is locked. No object level locking. Uses many locks.

  1. SynchronizedHashMap

Object level synchronization. Both read and write receive a lock. Collection lock has a performance flaw. May cause conflict

  1. Vector

  2. Hash table

  3. CopyOnWriteArrayList

  4. CopyOnWriteArraySet

  5. stack

The rest are all not thread safe

+6
source

ArrayList, LinkedList, HashSet, LinkedHashset and TreeSet in the collection interface and HashMap, LinkedHashMap and Treemap are not synchronized .

Vector in the synchronized collection interface

+4
source

The previous example is completely wrong.

First of all, you do not get access from different threads of the list that you just synchronized, you cannot prove that synchronization is working correctly, you cannot prove that the adding process is atomic. Secondly, a synchronized sentence on the list itself is bad practice; you don’t know if the optimizer will use the element in the list for synchronization, which will lead to unexpected behavior. In addition, synchronization is access to items in the read / write list, and not to the list itself. Take out Collections.synchronized and view the output. Try many times. Example:

 class ProcessSomething { private List<Integer> integerList = Collections.synchronizedList(new ArrayList<>()); private void calculate() { for (int i = 0; i < 10000; i++) { try { Thread.sleep(1); } catch (InterruptedException ex) { Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex); } integerList.add(new Random().nextInt(100)); } } private void calculate2() { for (int i = 0; i < 10000; i++) { try { Thread.sleep(1); } catch (InterruptedException ex) { Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex); } integerList.add(new Random().nextInt(100)); } } public void process() { Long start = System.currentTimeMillis(); Thread t1 = new Thread(new Runnable() { public void run() { calculate(); } }); t1.start(); Thread t2 = new Thread(new Runnable() { public void run() { calculate2(); } }); t2.start(); try { t1.join(); t2.join(); } catch (InterruptedException ex) { Logger.getLogger(ProcessSomething.class.getName()).log(Level.SEVERE, null, ex); } Long end = System.currentTimeMillis(); System.out.println("Duration: " + (end - start)); System.out.println("List size: " + integerList.size()); } } public class App { public static void main(String[] args) { new ProcessSomething().process(); } } 
+1
source

All collection classes (except Vector and Hashtable) in the java.util package are not thread-oriented. Only two old collections are thread-oriented: Vector and Hashtable. WHAT FOR? Here's the reason: synchronization can be very expensive! You know, Vector and Hashtable are two collections that existed in the early stages of the history of Java, and they were created for thread protection from the very beginning (if you have the opportunity to look at their source code, you will see that all their methods are synchronized!) . However, they quickly show poor performance in multithreaded programs. As you may know, synchronization requires locks, which always take time to monitor, which reduces performance. This is why new collections (List, Set, Map, etc.) generally do not provide concurrency management to ensure maximum performance in single-threaded applications.

+1
source

synchronization reduces performance. Of course, the Java collection is not in sync. but Java provides synchronization devices to synchronize the Java collection see link

 for example: import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; public class SynchronizedListExample { public static void main(String[] args) { List<String> syncList = Collections.synchronizedList(new ArrayList<String>()); syncList.add("one");//no need to synchronize here syncList.add("two"); syncList.add("three"); String st = syncList.get(0); //it is ok here => no need to synchronize // when iterating over a synchronized list, we need to synchronize access to the synchronized list //because if you don't synchronize here, synchList maybe be changed during iterating over it synchronized (syncList) { Iterator<String> iterator = syncList.iterator(); while (iterator.hasNext()) { System.out.println("item: " + iterator.next()); } } } } 
0
source

import java.util.Collections; // Import This

 List<String> syncList = Collections.synchronizedList(new ArrayList<String>()); 

Here's how you can sync a list in Java.

0
source

I assume that each collection API implementation is written in the documentation.

-3
source

Source: https://habr.com/ru/post/888419/


All Articles