Monday, August 25, 2014

Default Method in Interface - JDK 8

Default method: An interface declaration can contain method signatures, default methods, static methods and constant definitions. The only methods that have implementations are default and static methods

Default methods enable you to add new functionality to the interfaces of your libraries and ensure binary compatibility with code written for older versions of those interfaces

Best practices : Use default methods only in rare case. We have to choose default method name carefully to avoid compile time error in case of one class implementing two interfaces and both interfaces have same default method name.

Static method : Static methods are similar to default method. The only difference is that static method can not be overridden like default method by implementing class.

Functional Interface: Functional interface has exactly one abstract method. @FunctionalInterface annotation can be used to mark it as functional interface.


Thursday, June 26, 2014

HashMap and ConcurrentHashMap

We can syncronize HashMap as follows:

1: Collections.syncronizedMap(hashMap);

2: We can also use ConcurrentHashMap  if we need syncronized HashMap.

What are differences in these two syncronized HashMap.?

In 1:  gives a thread-safe HashMap backed by original HashMap and for each operation entire HashMap will be locked so that only one thread can  access the map.

In 2:  all operations are thread-safe and retrieval operation does not require locking of map.  While updating, only that portion of map is locked which  is being updated.

So performance wise 2: option is better than 1:

ConcurrentHashMap does not allow null key or value like Hashtable. The reason is if multiple threads will access the Map then it’s difficult to predict why key or value is null because it may be modified by other threads.
ConcurrentHashMap differs from Hashtable:
1: Hashtable is based on synchronization while ConcurrentHashMap works on concurrency.
2: Retrieval operation generally does not need any locking
3: Multiple threads can modify ConcurrentHashMap. By default it has concurrency level 16. It means 16 threads can update the table concurrently given that no two threads are working on same bucket. If it is the case then those threads will access that bucket in sequence.
4: It locks the bucket and not the whole map. ConcurrentHashMap uses Reentrant lock internally.
5: ConcurrentHashMap’s iterator is fail- safe.  It means Map can be modified externally while iterating but not in case of Hashtable.
6: ConcurrentHashMap uses balanced tree to store the next key value in case of hash collision while Hashtable uses LinkedList (Separate Chaining)

7: There are many useful methods that are present in ConcurrentHashMap (searchKeys, searchValues, newKeySet ) but not in Hashtable.