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
1
  • From the Hashtable 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 =) Commented Jun 19, 2014 at 16:51

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.