Tag Archives: synchronized

Java: Difference between HashMap and Hashtable

HashMap and Hashtable both implements Map interface and used to store data in key and value pairs. Both use hashing techniques to get unique keys.

Apart from some similarities, there are many differences between HashMap and Hashtable classes as follows:

java.util.HashMap java.util.HashTable
HashMap class introduced in JDK 1.2. Hashtable is a legacy class.
HashMap inherits AbstractMap class. Hashtable inherits Dictionary class.
HashMap is traversed by Iterator. Hashtable is traversed by the Enumerator and Iterator.
Hashmap, Iterator is fail-fast. Hashtable, Enumerator is not fail-fast.
HashMap is not synchronized and not-thread safe. Hashtable is synchronized and thread safe.
HashMap can be synchronized by calling this code
Map m = Collections.synchronizedMap(hashMap);
Hashtable is internally synchronized and can’t be unsynchronized.
HashMap class allows only one null key and multiple null values. Hashtable doesn’t allow any null key or value.
HashMap is fast. Hashtable is slow.

For more detail:


Java: Synchronized Collection Methods and Examples

In Collection Framework, only some of the classes are thread-safe or synchronized. If you need to work on a multi-threaded environment then you have to convert these non-synchronized type classes to Synchronized type collection.

Synchronized Collection

These are the classes only are synchronized:

  • Vector
  • HashTable

As a solution java.util.Collections class provides some static methods to make them Synchronized.

Collections Class Synchronized Methods

All these methods are static:

Collection synchronizedCollection(Collection c) Returns a synchronized collection.
List synchronizedList(List list) Returns a synchronized list.
synchronizedMap(Map<K,V> m)
Returns a synchronized map .
synchronizedNavigableMap(NavigableMap<K,V> m)
Returns a synchronized navigable map.
NavigableSet synchronizedNavigableSet(NavigableSet s) Returns a synchronized navigable set .
static Set synchronizedSet(Set s) Returns a synchronized set .
synchronizedSortedMap(SortedMap<K,V> m)
Returns a synchronized sorted map .
synchronizedSortedSet(SortedSet s)
Returns a synchronized sorted set.

Example: Synchronized Collections

In this example creating the blank type of collection and making it Synchronized. You can assign the same with collection objects.

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class CollectionSunchronizationExample {

	public static void main(String[] args) {
		Collection c = Collections.synchronizedCollection(new ArrayList());
	    List list = Collections.synchronizedList(new ArrayList());
	    Set s = Collections.synchronizedSet(new HashSet());
	    Map m = Collections.synchronizedMap(new HashMap());