Java Queue implementations

In general, Queue is “A collection designed for holding elements prior to processing. Besides basic Collection operations, queues provide additional insertion, extraction, and inspection operations.”

There are two main catalogs:

Ref:

ConcurrentHashMap, Hashtable and Synchronized Map in Java

All these three class can be used in the multiple thread environment. Here is a summary of the difference:

  • Hashtable is since Java 1.0. The implementation lock the whole table.
  • Synchronized Map is since Java 1.2 under Collection framework. Please refer to the best practice. You also need to lock the whole map.
  • ConcurrentHashMap is since Java 1.5 and also a member of Collection framework. The map is partitioned into segments based on concurrencyLevel. So each segment can have a lock to improve the performance.

A detail comparison is at: http://javarevisited.blogspot.sg/2011/04/difference-between-concurrenthashmap.html

Hashtable

“This class implements a hash table, which maps keys to values. Any non-null object can be used as a key or as a value.”

Synchronized Map

“It is imperative that the user manually synchronize on the returned map when iterating over any of its collection views:”

Map m = Collections.synchronizedMap(new HashMap());
      ...
  Set s = m.keySet();  // Needn't be in synchronized block
      ...
  synchronized (m) {  // Synchronizing on m, not s!
      Iterator i = s.iterator(); // Must be in synchronized block
      while (i.hasNext())
          foo(i.next());
  }

ConcurrentHashMap

“A hash table supporting full concurrency of retrievals and high expected concurrency for updates. This class obeys the same functional specification as Hashtable, and includes versions of methods corresponding to each method of Hashtable. However, even though all operations are thread-safe, retrieval operations do notentail locking, and there is not any support for locking the entire table in a way that prevents all access. This class is fully interoperable with Hashtable in programs that rely on its thread safety but not on its synchronization details.”

Always use putIfAbsent instead of following code to achieve atomic action and better performance:

if (!map.containsKey(key))
   return map.put(key, value);
 else
   return map.get(key);

Ref