0

What is synchronized collection means in java . Which to choose for developing application if i am printing records of user in jsp page from servlet?which to choose among the following

  1. HashMap
  2. Hash Table
srinivas
  • 474
  • 7
  • 14
  • From the [Hashtable](http://docs.oracle.com/javase/7/docs/api/index.html?java/util/Collections.html) javadoc: "If a thread-safe implementation is not needed, it is recommended to use HashMap in place of Hashtable. If a thread-safe highly-concurrent implementation is desired, then it is recommended to use ConcurrentHashMap in place of Hashtable." This class comes from Java2 and was retrofitted, don't use it =) – NiziL Jun 19 '14 at 16:51

2 Answers2

1

Synchronization is the capability to control the access of multiple threads to any shared resource.

The synchronized collections classes Hashtable and Vector, and static methods of the java.util.Collections class synchronizedCollection(),synchronizedSet(), synchronizedSortedMap(),synchronizedSortedSet() provide a basic conditionally thread-safe implementation of Map, List and Set.

As the Javadocs says - If a thread-safe implementation is not needed, it is recommended to use HashMap in place of Hashtable. If a thread-safe highly-concurrent implementation is desired, then it is recommended to use ConcurrentHashMap in place of Hashtable.

Difference between Hashtable and ConcurrentHashMap : ConcurrentHashMap only locked certain portion of Map while Hashtable lock full map while doing iteration

ConcurrentHashMap is designed for concurrency and improve performance while HashMap which is non synchronized by nature can be synchronized by applying a wrapper using Collections.synchronizedMap().

Difference : ConcurrentHashMap do not allow null key or null values while HashMap allows null key.

SparkOn
  • 8,806
  • 4
  • 29
  • 34
0

A synchronized collection is one that is thread-safe for concurrent updates from multiple threads. In general, in Java:

  • Never use Hashtable. Use ConcurrentHashMap instead. Even though Hashtable is thread-safe, ConcurrentHashMap has better performance and offers the same concurrency guarantees.
  • Favour HashMap if you do not need concurrency (i.e. the map will only be used by one thread)

As for the JSP question, it really depends. If you're sharing the same map instance across multiple threads (like, if it's "global" in the application) then use ConcurrentHashMap. If you create it in a request, then get rid of it when you're done, and it's never used in another thread, then just use HashMap.

There are some more details in this question too.

Community
  • 1
  • 1
Jonathan
  • 7,536
  • 4
  • 30
  • 44