What are the differences between a HashMap and a Hashtable in Java?

What are the differences between a HashMap and a Hashtable in Java?

Which is more efficient for non-threaded applications?

  • 38
    HashTable is obsolete in Java 1.7 and it is recommended to use ConcurrentMap implementation  Apr 9, 2017 at 22:10
  • 9
    @MissFiona No, ConcurrentMap is notnecessary here, as the Question says “non-threaded applications” meaning threading/concurrency is not an issue. Dec 29, 2019 at 1:11 
  • 4
    @BasilBourque, Yes, but I believe what MissFiona meant by that was something akin to "HashTable has traditionally been only chosen because of its partial threading protection. But that's been obviated by ConcurrentHashMap, so it's generally regarded as retired. It's generally recommended to choose between HashMap or ConcurrentHashMap." And I believe that to be a sensible comment, if it's what she meant. 
    – alife
     Feb 27 at 17:26 
  • According to doi.org/10.48550/arXiv.1602.00984Hashtable is more efficient than HashMap in terms of both energy consumption and execution time.  Jun 29 at 19:36

Comments

  1. There are several differences between HashMap and Hashtable in Java:

    Hashtable is synchronized, whereas HashMap is not. This makes HashMap better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones.

    Hashtable does not allow null keys or values. HashMap allows one null key and any number of null values.

    One of HashMap's subclasses is LinkedHashMap, so in the event that you'd want predictable iteration order (which is insertion order by default), you could easily swap out the HashMap for a LinkedHashMap. This wouldn't be as easy if you were using Hashtable.

    Since synchronization is not an issue for you, I'd recommend HashMap. If synchronization becomes an issue, you may also look at ConcurrentHashMap.

    ReplyDelete
    Replies
    1. If you want to make a HashMap thread-safe, use Collections.synchronizedMap(). –
      Rok StrniĊĦa
      Nov 22, 2011 at 18:48
      336
      I would also comment that the naive approach to thread-safety in Hashtable ("synchronizing every method should take care of any concurrency problems!") makes it very much worse for threaded applications. You're better off externally synchronizing a HashMap (and thinking about the consequences), or using a ConcurrentMap implementation (and exploiting its extended API for concurrency). Bottom line: the only reason to use Hashtable is when a legacy API (from ca. 1996) requires it. –
      erickson
      Mar 16, 2012 at 17:19
      8
      HashMap gives flexibility to programmer to write threadSafe code when they actually use it. It happened rarely that I needed a thread safe collection like ConcurrentHashMap or HashTable. What I needed is certain set of functions or certain statements in a synchronized block to be threadsafe. –
      Gaurava Agarwal
      Jun 27, 2016 at 9:00
      6
      Hashtable is obsolete and we are using HashMap for non thread safe environment. If you need thread safety then you can use Collections.synchronizedMap() or use ConcurrentHashMap which is more efficient that hashtable. –
      Maneesh Kumar
      Mar 30, 2018 at 3:45
      5
      It's obsolete but not deprecated and I'm wondering why this is. I'm guessing removing this class (and Vector for the same reasons) would break too much existing code and annotating with @Deprecated would imply an intention to remove the code, which apparently is not there. –
      Jilles van Gurp
      May 19, 2018 at 8:11
      1
      You can also use ConcurrentSkipListMap (docs.oracle.com/javase/10/docs/api/java/util/concurrent/…). It is thread-safe collection similar to ConcurrentHashMap and this map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time. –
      rashid
      Jun 25, 2018 at 7:25
      1
      HashTable use single intrinsic lock which result in very poor performance in even in low contention. While Threadsfe counterpart of HashMap i.e. ConcurrentHashMap use lock spliting which is user configurable has multitime better performance even in high contention. –
      Gajraj Tanwar
      May 3, 2021 at 10:09

      Delete
  2. Note, that a lot of the answers state that Hashtable is synchronized. In practice this buys you very little. The synchronization is on the accessor/mutator methods will stop two threads adding or removing from the map concurrently, but in the real world, you will often need additional synchronization.

    A very common idiom is to "check then put" — i.e. look for an entry in the Map, and add it if it does not already exist. This is not in any way an atomic operation whether you use Hashtable or HashMap.

    An equivalently synchronised HashMap can be obtained by:

    Collections.synchronizedMap(myMap);
    But to correctly implement this logic you need additional synchronisation of the form:

    synchronized(myMap) {
    if (!myMap.containsKey("tomato"))
    myMap.put("tomato", "red");
    }
    Even iterating over a Hashtable's entries (or a HashMap obtained by Collections.synchronizedMap) is not thread-safe unless you also guard the Map against being modified through additional synchronization.

    Implementations of the ConcurrentMap interface (for example ConcurrentHashMap) solve some of this by including thread safe check-then-act semantics such as:

    ConcurrentMap.putIfAbsent(key, value);

    ReplyDelete
  3. Hashtable is considered legacy code. There's nothing about Hashtable that can't be done using HashMap or derivations of HashMap, so for new code, I don't see any justification for going back to Hashtable.

    ReplyDelete
  4. This question is often asked in interviews to check whether the candidate understands the correct usage of collection classes and is aware of alternative solutions available.

    The HashMap class is roughly equivalent to Hashtable, except that it is non synchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesn't allow nulls).
    HashMap does not guarantee that the order of the map will remain constant over time.
    HashMap is non synchronized whereas Hashtable is synchronized.
    Iterator in the HashMap is fail-safe while the enumerator for the Hashtable is not and throw ConcurrentModificationException if any other Thread modifies the map structurally by adding or removing any element except Iterator's own remove() method. But this is not a guaranteed behavior and will be done by JVM on best effort.
    Note on Some Important Terms:

    Synchronized means only one thread can modify a hash table at one point in time. Basically, it means that any thread before performing an update on a Hashtable will have to acquire a lock on the object while others will wait for the lock to be released.
    Fail-safe is relevant within the context of iterators. If an iterator has been created on a collection object and some other thread tries to modify the collection object "structurally", a concurrent modification exception will be thrown. It is possible for other threads though to invoke the set method since it doesn't modify the collection "structurally". However, if prior to calling set, the collection has been modified structurally, IllegalArgumentException will be thrown.
    Structurally modification means deleting or inserting element which could effectively change the structure of the map.
    HashMap can be synchronized by

    Map m = Collections.synchronizeMap(hashMap);

    Map provides Collection views instead of direct support for iteration via Enumeration objects. Collection views greatly enhance the expressiveness of the interface, as discussed later in this section. Map allows you to iterate over keys, values, or key-value pairs; Hashtable does not provide the third option. Map provides a safe way to remove entries in the midst of iteration; Hashtable did not. Finally, Map fixes a minor deficiency in the Hashtable interface. Hashtable has a method called contains, which returns true if the Hashtable contains a given value. Given its name, you'd expect this method to return true if the Hashtable contained a given key because the key is the primary access mechanism for a Hashtable. The Map interface eliminates this source of confusion by renaming the method containsValue. Also, this improves the interface's consistency — containsValue parallels containsKey.

    The Map Interface

    ReplyDelete

Post a Comment

Popular posts from this blog

How do I generate random integers within a specific range in Java?

#1 javascript toturial

Proper use cases for Android UserManager.isUserAGoat()?