Tuesday, October 7, 2008

Fail-Safe concept in collection

1. Difference between Hashtable and HashMap.
  • Hashtable is synchronized, HashMap is not.
  • Iterator in the HashMap is fail-safe (meaning, it throws ConcurrentModificationException when try to add a value to the collection while iterating), but the enumeration for Hashtable is not fail-safe.
  • HashMap points null values, while Hashtable doesn't.

If you want to synchronize a HashMap write the following code.
Map map = Collections.synchronizedMap(new HashMap());

2. Vector vs ArrayList.
  • Vector is synchronized, ArrayList is not
  • Iterator that are returned by both classes are fail-safe. Enumeration returned by Vector are not.
If you want to synchronize an ArrayList write the following code.
List list = Collections.synchronizedList(new ArrayList());

1 Comments:

Blogger javin paul said...

Concept of fail-safe iterator are relatively new in Java and first introduced with Concurrent Collections in Java 5 like ConcurrentHashMap, CopyOnWriteArrayList and Doesn't throw ConcurrentModificationException does eliminate need of further locking and improves concurrency.
source: Fail Safe vs Fail Fast Iterator Java

February 16, 2012 at 5:07 AM  

Post a Comment

Subscribe to Post Comments [Atom]

<< Home