1 – Difference between HashTable and HashMap
- HashMap is not threadsafe whereas HashTable is threadsafe
- Since HashMap is not synchronized it performs better than HashTable
- Hashtable does not allow null key, hashmap allows 1 null key & several null values
- Iterator in hashmap is fail-fast. But enum in Hashtable is not fail-fast. Fail-fast means if one thread is iterating over a map and another is trying to modify it by adding/deleting elements, it will throw ConcurrentModificationException.
2 – Explain how HashMap works in Java.
- HashMap works on the principle of hashing
- put() and get() methods are used to store and retrieve data from hashmap
- it has a number of buckets which stores key-value pairs
- when put() is called, hashmap implementation calls hashcode() on the key to identify the bucket location… then stores both key+value in the bucket
- when get() is called, the hashcode() on key is used to identify the bucket location and the value if returned.
- If two key objects have same hashcode, bucket location will be the same and collision occurs in hashmap.
- Inside the bucket, data is stored in linked list, so in collision scenario, it will get added to next node.
- So, when get() is called, the hashcode() would point to the bucket location, then the use key.equals() to find the correct node in the linked list.
3 – How to Synchronize a HashMap ?
- HashMap can be synchronized by calling Collections.getSynchronizedMap(hashmap);
4 – Why we need ConcurrentHashMap and CopyOnWriteArrayList ?
The synchronized collections classes, Hashtable and Vector, and the synchronized wrapper classes, Collections.synchronizedMap and Collections.synchronizedList, provide a basic conditionally thread-safe implementation of Map and List. However, several factors make them unsuitable for use in highly concurrent applications for example their single collection-wide lock is an impediment to scalability and it often becomes necessary to lock a collection for a considerable time during iteration to prevent ConcurrentModificationException.
ConcurrentHashMap and CopyOnWriteArrayList implementations provide much higher concurrency while preserving thread safety, with some minor compromises in their promises to callers. ConcurrentHashMap and CopyOnWriteArrayList are not necessarily useful everywhere you might use HashMap or ArrayList, but are designed to optimize specific common situations. Many concurrent applications will benefit from their use.
5- What is ConcurrentHashMap in java ?
- Best suited when you have multiple readers and few writers. Otherwise, performance degrades to synchronized map or hashtable
- allows multiple users to read simultaneously without any blocking
- this is achieved by partitioning map into different parts depending on concurrency level and locking only a portion of the map during updates.
- Since update operations like put(), remove(), putall(),clear() are not synchronized, concurrent retrieval may not reflect most recent change on the map.
- All operations on concurrent hashmap are threadsafe.
6 – What is CopyOnArrayList in java ?
- creates a copy of underlying arraylist with every mutating operation ,i.e. add or set.
- Normally very expensive as it involves costly array copy with every write operation. Use when iteration is more than mutation.
- iterator is fail-safe
7 – Explain use of WeakHashMap in java.
- map implementation that stores only weak references to its keys
- this allows a key-value pair to be garbage collected when key is no longer reachable by any thread
- useful for implementing “registry” like data structures where the utility of the entry vanishes when its no longer referenced
8 – Why return type of hashcode() is int and not long ?
- The maximum length of an array is Integer.MAX_VALUE
- Since the primary use of hashcode() is to determine in which slot to insert an object into the backing array of hashtable/hashmap, a hashcode greater than Integet.MAX_VALUE can not be stored in an array
9 – Compare Sorted vs Ordered Collections in java.
When a collections is ordered, it means you can iterate through the collection in a specific order,
A Hashtable collection is not ordered, where as an ArrayList is ordered by elements index position and LinkedHashMap is ordered by the insertion order.
Some collections keep an order referred as natural order of elements.. those collections are not just ordered, they are sorted. The natural order is specified the Comparable interface. But it is also possible to define other sort orders using Comparator interface
10 – Why String, Integer and other wrapper classes are considered good keys ?
String, Integer and other wrapper classes are natural candidates of HashMap key, and String is most frequently used key as well because String is immutable and final,and overrides equals and hashcode() method.
Other wrapper class also shares similar property.
Immutabiility is required, in order to prevent changes on fields used to calculate hashCode() because if key object return different hashCode during insertion and retrieval than it won’t be possible to get object from HashMap. Immutability is best as it offers other advantages as well like thread-safety,
If you can keep your hashCode same by only making certain fields final, then you go for that as well. Since equals() and hashCode() method is used during reterival of value object from HashMap, its important that key object correctly override these methods and follow contact. If unequal object return different hashcode than chances of collision will be less which subsequently improve performance of HashMap.
11 – Can we use any custom object as key in HashMap ?
We can use any Object as key in Java HashMap provided it follows equals and hashCode contract and its hashCode should not vary once the object is inserted into Map. If custom object is Immutable than this will be already taken care because you can not change it once created.
12 – Difference between ConcurrentHashMap and Hashtable
Both can be used in multithreaded environment but once the size of Hashtable becomes considerable large performance degrade because for iteration it has to be locked for longer duration.
Since ConcurrentHashMap introduced concept of segmentation , no matter how large it becomes only certain part of it get locked to provide thread safety so many other readers can still access map without waiting for iteration to complete.
In Summary ConcurrentHashMap only locked certain portion of Map while Hashtable lock full map while doing iteration.
13 – Can we use ConcurrentHashMap in place of Hashtable ?
Hashtable is synchronized but ConcurrentHashMap provides better concurrency by only locking portion of map determined by concurrency level. ConcurrentHashMap is certainly introduced after Hashtable and can be used in place of it but Hashtable provide stronger thread-safety than ConcurrentHashMap.
14 – Difference between ConcurrentHashMap and Collections.synchronizedMap
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.
© 2015 – 2016, www.topjavatutorial.com. All rights reserved. On republishing this post, you must provide link to original post