Saturday, March 5, 2016

Java Study Notes 1

The constructors and initializers cannot be synchronized and a compiler error will occur if you put synchronized front of a constructor. But constructors and initializers of a class can contain synchronized blocks The interface's methods cannot be declared synchronized. The Synchronization is part of the implementation but not part of the interface.

Can float and double value represent decimal number exactly?

The int and long type do represent integral numbers exactly, but the value of float and double type do not represent decimal numbers exactly.
The float and double perform binary floating-point arithmetic. It only provide approximate of the results of arithmetic operations because they are binary and cannot exactly represent negative powers of then (i.e., 10 -1); If you want an exact representation you can use the java.math.BigDecimal class. For example,
import java.math.BigDecimal;

public class Change {

  public static void main(String args[]) {

    BigDecimal bigD1 = new BigDecimal("2.00");

    BigDecimal bigD2 = new BigDecimal("1.10"); 

    System.out.println(bigD1.subtract(bigD2));

  }

}

Are true, false, and null Java keywords?

The true, false, and null are not Java keywords, but they are reserved words. Remember that all keywords are reserved words, but not vice versa. Java keywords and reserved words can not be used as identifiers such as variable, class, or method names.
Java Language Specification has differentiated between the two to specify that reserved literals represents a value for a primitive,object or null type. On the other hand, you cannot assign keywords as values to primitives,objects or null type.

LinkedHashMap vs. HashMap?

  • A LinkedHashMap differs from HashMap in that the order of elements is maintained.
  • A HashMap has a better performance than a LinkedHashMap because a LinkedHashMap needs the expense of maintaining the linked list. The LinkedHashMap implements a normal hashtable, but with the added benefit of the keys of the hashtable being stored as a doubly-linked list.
  • Both of their methods are not synchronized.
Let's take a look their API documentations:
The HashMap is a hash table with buckets in each hash slot. Like in the API documentation:
This implementation provides constant-time performance for the basic operations (get and put), assuming the hash function disperses the elements properly among the buckets. Iteration over collection views requires time proportional to the "capacity" of the HashMap instance (the number of buckets) plus its size (the number of key-value mappings). Thus, it's very important not to set the initial capacity too high (or the load factor too low) if iteration performance is important.
The LinkedHashMap is a linked list implementing the map interface. As said in the API documentation:
Hash table and linked list implementation of the Map interface, with predictable iteration order. This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order).
Capacity of any collection class is the maximum number of elements collection can hold. size of collection must be less than or equal to its capacity. Though in reality, collection resize themselves even before it reaches its capacity, controlled by laod factor.

The initial capacity is nothing but the number of buckets when the hash table is created, capacity is automatically increased when hash table get full of element.
 Load factor is a measurement of how full hash table is allowed or number of elements in the hash table. When the hash table gets full of element its capacity automatically gets increased.

Difference between array and arraylist
1.       Array is static; its fixed size and cant change once created. ArrayList is dynamic; it can be resizable.
2.       ArrayList is a class from collections framework but array is native programming component
3.       Array can store primitives as well as objects and array list will store only the wrapper classes.
4.       Array is not generic but arraylist is
5.       We can remove element from arraylist but not from array.
6.       Array can be multidimensional and arraylist is one dimensional
7.       Array provide length attribute and arraylist provides size() method but both are different, length is capacity and size return number of elements.

Map is one of the most important interface in collection framework. It provide the hash table data structure functionality by using hashmap, linked hashmap, treemap, etc.,
If the map already contains a mapping for the key, the old value is replaced.

Hashmap is used to store the key and value pairs using hashing based datastructure. It doesn’t provide any ordering. It allows one null key and many null values.
Treemap based on NavigableMap implementation provides you sorting, on top of hashing. It doesn’t allow null keys.
LinkedHashmap maintaining mappings in order as they are inserted into Map. It also allows null keys and values.
EnumMap – storing mapping with enum constants as keys.
WeakHashMap – creating a garbage collector friendly cache, where values become eligible for garbage collection as soon as there is no other reference to them apart from keys in weakhashmap.
IdentityHashMap – used to creating a map which uses identity instead of equality for comparing keys since identity equality is rare, you get less number of collisions.
ConcurrentHashMap – It is used in concurrent programming. Multiple reader can access the Map concurrently  while a portion of Map gets locked for write operation. Its fail safe while doing iteration of elements which doesn’t throw ConcurrentModificationException.

CopyOnWriteArrayList achieves thread-safety by creating a separate copy of List for each write operation.Its similar to concurrenthashmap and can say it’s the replacement for synchronized arraylist.

BlockingQueue makes it easy to implement producer-consumer design pattern by providing inbuilt blocking support for put() and take() method. put() method will block if Queue is full while take() method will block if Queue is empty. ava 5 API provides two concrete implementation of BlockingQueue in form of ArrayBlockingQueue and LinkedBlockingQueue, both of them implement FIFO ordering of element. ArrayBlockingQueue is backed by Array and its bounded in nature while LinkedBlockingQueue is optionally bounded.

Deque and BlockingDeque
Deque interface is added in Java 6 and it extends Queue interface to support insertion and removal from both end of Queue referred as head and tail. Java6 also provides concurrent implementation of Deque like ArrayDeque and LinkedBlockingDeque. Deque Can be used efficiently to increase parallelism in program by allowing set of worker thread to help each other by taking some of work load from other thread by utilizing Deque double end consumption property.

ConcurrentSkipListMap and ConcurrentSkipListSet provide concurrent alternative for synchronized version of SortedMap and SortedSet. For example instead of using TreeMap or TreeSet wrapped inside synchronized Collection, You can consider using ConcurrentSkipListMap or ConcurrentSkipListSet from java.util.concurrent package.

NavigableMap in Java 6 is an extension of SortedMap  like TreeMap which provides convenient navigation method like lowerKey, floorKey, ceilingKey and higherKey. NavigableMap is added on Java 1.6 and along with these popular navigation method it also provide ways to create a Sub Map from existing Map in Java e.g. headMap whose keys are less than specified key, tailMap whose keys are greater than specified key and a subMap which is strictly contains keys which falls between toKey and fromKey.

Race conditions occurs when two thread operate on same object without proper synchronization and there operation interleaves on each other.
Object Serialization in Java is a process used to convert Object into a binary format which can be persisted into disk or sent over network to any other running Java virtual machine; the reverse process of creating object from binary stream is called deserialization in Java. Java provides Serialization API for serializing and deserializing object which includes java.io.Serializable, java.io.Externalizable, ObjectInputStream and ObjectOutputStream

What is difference between start and run method? Main difference is that when program calls start() method a new Thread is created and code inside run() method is executed in new Thread while if you call run() method directly no new Thread is created and code inside run() will execute on current Thread.

What is deadlock?
Answer is simple, when two or more threads are waiting for each other to release lock and get stuck for infinite time, situation is called deadlock . It will only happen in case of multitasking.
E.g.,
Method1(){
Synchronized(String.class){
System.out.println(“acquire lock for string class”);
Synchronized(Integer.class){
System.out.println(“acquire lock for integer class”)
}
       }
}
Method2(){
Synchronized(Integer.class){
System.out.println(“acquire lock for string class”);
Synchronized(String.class){
System.out.println(“acquire lock for integer class”)
}
       }
}

CountDownLatch and CyclicBarrier in Java are two important concurrency utility which is added on Java 5 Concurrency API. Both are used to implement scenario, where one thread has to wait for other thread before starting processing but there is difference between them. Key point to mention, while answering this question is that CountDownLatch is not reusable once count reaches to zero, while CyclicBarrier can be reused even after barrier is broken.

No comments: