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
- HashMap
- Hash Table
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
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.
A synchronized collection is one that is thread-safe for concurrent updates from multiple threads. In general, in Java:
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.