Thursday, September 15, 2016

Thread

  1. Thread can be implemented either extending Thread Class or implementing Runnable Interface. Since we can’t extend 2 classes in Java implementing Runnable is better option
  2. States of Thread
·         New: The thread is created
·         Runnable: thread is runnable only after start() method
·         Running: thread is executing after run() method
·         Waiting/Blocked: thread is waiting for other thread to finish job. Once wait is over, it’s state is changed to runnable and it’s moved back to runnable thread pool
·         Dead: once thread finished executing, it’s state is changed to dead and it is not considered alive
·         start() and run(): start() internally calls the run() method. While we use start() method a new thread is created when run() is called internally to start(). But when we call run() method separately, it is executed in same thread.
  1. Object class has 3 final methods that allow thread to communicate about lock status of thread
·         wait(): has 3 variances. In one it waits indefinitely and call notify() notifyAll() method to wake up current thread. In other two the thread wait for a definite amout
·         notify(): wakes up only 1 thread waiting on an object and then that thread execution starts. If multiple threads are waiting on an object the method wakes up only 1 thread. Which thread will wake up is decided by OS implementation of thread management.
·         notifyAll(): wakes up all the threads waiting on the object. But which thread will execute first will depend on OS implementation. It is usually implemented in producer consumer problems.
·         join(): used to pause the current thread execution until unless specified thread is dead
thread1.join(); thread2.start() à thread two will start only after thread 1 is dead
thread1.join(2000); thread2.start() àthread two will start only after 2 sec or thread 1 is dead
  1. Message: A java class on which thread will work and call the wait() notify() methods
  2. Waiter: A class which will wait for other threads to invoke notify methods to complete its processing. Waiter thread is owning monitor on Message object using synchronized block
  3. Runnable and Callable: runnable from JDK1.0 while callable is from JDK 1.5. Callable’s call() can return value and throw exception which is not possible in Runnable’s run(). Callable return future object, which can hold result of a computation.
  4. For multithreaded environment thread safety a concern since updating an element is 3 steps process, taking the variable editing it and writing back. Threadsafety can be assured either by
·         Synchronization
·         Using atomic interger instead of ++
AtomicInteger atomicCount = new AtomicInteger( 0 );


  1. Thread safe by default in Java
·         Immutable objects like String
·         Read-only or final variables
·         Static variables if not initialized properly become major cause of thread-safety issues
·         Thread-safe classes like: Vector; Hashtable; ConcurrentHashMap; String
·         Atomic operation are thread-safe
·         Local variables are thread-safe
·         Volatile keyword for variables
  1. Also JVM plays a spoiler since it can reorder code for optimization, so the code which looks sequential and runs fine in development environment not guaranteed to run similarly in production environment because JVM may ergonomically adjust itself as server JVM and perform more optimization and reorder which cause thread-safety issues.

  1. When we create a Thread in java, by default it’s a user thread and if it’s running JVM will not terminate the program. When a thread is marked as daemon thread, JVM doesn’t wait it to finish and as soon as all the user threads are finished, it terminates the program as well as all the associated daemon threads.
        Thread dt = new Thread(new DaemonThread(), "dt");dt.setDaemon(true);

  1. Deadlock: when multiple threads are waiting for each other to release the resource thus causing cyclic dependency

  1. We can share data between two threads by using shared objects or concurrent data structures like Blocking queue. For ex. Consumer producer pattern. JavaBlocking Queue is a java Queue that support operations that wait for the queue to become non-empty when retrieving and removing an element, and wait for space to become available in the queue when adding an element.

  1. Java thread pool manages the pool of worker threads, it contains a queue that keeps tasks waiting to get executed. We can use ThreadPoolExecutor to create thread pool in java.

Wednesday, September 14, 2016

Synchronization

      1. Important in case of multi-threaded environment
      2. Synchronization can be of Java Object or Java Class
      3. Synchronized and volatile keywords are used for synchronizing i.e. mutual exclusive access
      4. Concurrent access of shared objects introduces errors like thread interference and memory consistency. To avoid these errors object must be synchronized
      5. If shared object is read-only or immutable like ‘String’ then synchronization not required despite running multiple threads
      6. JVM guarantees java synchronized code is executed one at a time
      7. synchronized keyword is related to locking and unlocking. When entering the synchronized block or method it needs to acquire lock so it reads from main memory rather than cache memory. When exiting the synchronized block or method it needs to release the lock so it flushes write operation in main memory. This eliminates memory consistency errors.
      8. Any code with synchronized method or synchronized block is mutually exclusive
      9. static synchronized method and non-static synchronized method. In Static synchronized method class object is locked (class level lock) where as in non-static synchronized current object (this) is locked (object level lock). If we have a non-static and static method on same object/ scenario, they can run in parallel since one will run on class object and other on this object.
      public class Counter{ 
      private static int count = 0; 
      public static synchronized int getCount(){ return count;}
                  public synchoronized setCount(int count){ this.count = count; } }

      1. can’t have synchronized variable it gives compilation error. So we can have volatile variable since this reads variable from main memory rather than cache
      2. block synchronization preferred over method since only the required part is made mutually exclusive since it comes at the cost of performance
      3. if object used inside synchronized block is null then nullpointer exception is thrown
      4. java synchronized keyword is re-entrant in nature
      5. does not allow concurrent read. By using concept of lock stripping and using different locks for read and write we can overcome this limitation.
      6. synchronized keyword is used to limited access in only 1 JVM. If there are different JVM or different file bases or DB, synchronized keyword does not work and we need to implement global locks.
      7. Can result in dead-lock or starvation in multi threading is synchronization not properly implemented.
      8. Constructor can’t be synchronized
      9.  Important methods related to synchronization: wait(), notify(), notifyAll() which is defined in ObjectClass
      10. Don’t synchronize non-final fields in synchronized block since the value can change at any time and then different threads may be synchronizing different objects
      11. String is not recommended as a lock in java synchronized block because a string is an immutable object and literal string and interned string gets stored in String pool. so by any chance if any other part of the code or any third party library used same String as there lock then they both will be locked on the same object despite being completely unrelated which could result in unexpected behavior and bad performance. Instead of String object its advised to use new Object() for Synchronization in Java on synchronized block.
      private static final String LOCK = "lock";   //not recommended
         private static final Object OBJ_LOCK = new Object(); //better
         public void process() {
                                        synchronized(LOCK) {
                                                       .......
            }
         }
      1. Calendar and SimpleDateFormat classes are not thread-safe and require external synchronization in multi-threaded environment
      2.  
                     private static final String LOCK = "lock";   //not recommended
                     private static final Object OBJ_LOCK = new Object(); //better
                     public void process() {
                                     synchronized(LOCK) {
                                                    .......
                        }
                     }

Tuesday, September 13, 2016

ArrayList LinkedList

1.      Array has fixed length <-> arraylist is dynam
2.      Stored in contiguous memory location in Java Heap  

  1. 1.      Vector and ArrayList are index based and backed up by an array internally.
    2.      Both ArrayList and Vector maintains the insertion order of element. Means you can assume that you will get the object in the order you have inserted if you iterate over ArrayList or Vector
    3.      Both Iterator and ListIterator returned by ArrayList and Vector are fail-fast.
    4.      ArrayList and Vector also allows null and duplicates.



Sunday, September 11, 2016

Static Keyword



1.       static defines class level and not instance level
2.       used for static variables/ static methods/ static block/ static inner class/ Interface static method(only Java 8 onwards)

Static Variables:
1.       class variable and not object/instance variable
2.       since shared across all instances of Object NOT THREAD SAFE
3.       usually, used with final keyword
4.       if not private, can be accessed with ClassName.variableName
       private static int i;

Static Method:
1.       Can access only static variables of the class and invoke only static methods
2.       Usually utility methods which we want to expose to other class without creating an instance of the class
      private static countA();

Static Block:
1.       Gets executed when the class gets loaded in the memory by Java ClassLoader
2.       Used to initialize static variables of the class
3.       Can’t access non-static variables  in static block
4.       Can have multiple static blocks in a class

Static Class:
1.       It is a nested class
2.       Can’t use nested on the outer class
j
    Java Static Import:
    From Java 1.5 we can import static members methods & variables in another class
    import static com.PackageName.ClassName.variableName;
    import static com.PackageName.ClassName.methodName; -- no need to give ()




Friday, September 9, 2016

Classes In Java

·         Abstract Class
1.       Similar to Interface except method can have body
2.       Can’t be instantiated but it can have constructors. The purpose is to initialize final variables from subclass (lazy initialization)
3.       abstract keyword used to create abstract method
4.       Subclass should implement all abstract method unless subclass is also abstract
5.   Can have constructor. 
public abstract class A{
private String s;
public void method1(){s=’Sample’};
public abstract void method2();
}

public class B extends A{
private String str;
public void method2(){str=’Subclass’};
}

·         Wrapper Class
1.       All wrapper classes in Java are immutable and final
2.       Primitive<-> Wrapper (byte<->Byte, short<->Short, int<->Integer, long<->Long, float <->Float, double <-> Double, char <-> Character, Boolean <-> Boolean)
3.       Primitive types can’t be null but wrapper classes can be. int=null Int=Null

Nested classes are of Two Types of nested classes
 Java Static Class
 Java Inner Class

·                                       Static Class:
1.       static class Test{} : wrong compilation error will come.
2.       Java doesn’t allow top level static class
3.       Java supports nested classes which can be static
4.       static nested class can access only static members of outer class
5.       3 class files are created. OuterClass.class; StaticNestedClass.class. Static class file is created as OuterClass$StaticNestedClass.class
6.       The only possible benefit is encapsulation
public class OuterClass(){
                private static String st=’str’;
                static class StaticNestedClass(){
                                private int a;
                                public int getA(){};
                                public String getSt(){return st};
                }
}

public class Test(){
                public static void main(String[] args){
                                OuterClass.StaticNestedClass snc=new OuterClass.StaticNestedClass();
                                System.out.println(snc.getST()); --- accessing static member of outer class
                }
}

·         Java Inner Class:
1.       Inner class is defined inside body of a class
2.       Can be private, public, protected, or with default access whereas outer class can have only public or default access
3.       Any non-static inner class
4.       Associated with the object of that class and can access all variables and methods of that class
5.       Can’t have any static variable in these
OuterClass outerObj=new OuterClass();
OuterClass.InnerClass innerObj=outerObj.new InnerClass();

Wednesday, September 7, 2016

Collection Framework

Collection

  • Containers that group multiple items in a single unit
  • Collection framework is architecture to represent and manipulate collections in java in standard way
  • Collection FW consists of Interfaces/Implementation Classes/Algorithm

Java Collection Interfaces:
  • Foundation of Java collection framework
  • If unsupported operation is invoked, a collection implementation throws an UnsupportedOperationException
1.      Collection Interface: No direct implementation of this interface. 
2.      Iterator Interface: Used to iterate over any collection
3.      Set Interface: Can't have duplicates. Doesn't allow random access to an element. We need to use iterator or for-each to traverse the elements of set.
4.      List Interface: Ordered collection which can have duplicates. Elements can be accessed using index. More like array with dynamic length.
5.      Queue Interface: used to hold values before processing
6.      Dequeue Interface
7.      Map Interface: key to value pair. Can’t contain duplicate keys. Key and value are 1:1. Implementation are HashMap, TreeMap and LinkedHashMap
8.      ListIterator Interface: Used to traverse the list in either direction, modify the list during traversal and obtain iterator’s current position. Does not have any current element. Its position lies in between elements. previous() returns the previous element and next() returns the next element.
9.      SortedSet Interface: Ordered set in ascending order
10.  SortedMap Interface: Ordered map in ascending order based in key

Collection Interface: No direct implementation of this interface. Common methods:  
  • int size(), 
  • boolean isEmpty(), boolean contains(Object o), boolean add(E e), boolean remove (Object o)
  • Iterator<E> iterator()
  • Bulk operation : boolean containsAll(Collection<?>), boolean addAll(Collection<? extends E> c),boolean retainAll(Collection<?> c),boolean removeAll(Collection<?> c), void clear()


Java Collection Classes:
  • Usually not thread-safe
  • Their iterator is fail-fast (iterator fails as soon as structure of collection has been changed since iteration has begun. Structural changes mean adding, removing updating any element from collection while one thread is iterating over that collection). ConcurrentModificationException is thrown
1.      ArrayList:
a.      Resizable-array implementation of List Interface
b.      Allows null and duplicates
c.       Unsynchronized so better performance than Vector in single threaded environment
d.      Objects added in order
e.      Default capacity=10 but can be changed using ensureCapacity(int minCapacity) method.
f.        ArrayListInterator and ListIterator are fail-fast
g.      Supports generics
List list = new ArrayList() – not recommended
List<String> list = new ArrayList<String>(); -- recommended

2.      LinkedList:
a.      Implementation of List and Dequeue interfaces
b.      Permits null
c.       Operations that index into the list will traverse the list from beginning or the end, whichever is closer to the specified index.

3.      HashMap: works on hashing algorithm.
a.      Allows null key and values
b.      Not ordered collection and iterate over hashmap based on key but keys not guaranteed in order of insertion
c.       Not synchronized
d.      Stores entries in multiple singly linked lists called buckets. Default number of bins is 16 and it is always power of 2
e.      Uses inner class Node<K,V> for storing map entries
f.        Uses hashcode() and equal() methods on keys for get() and put() operations.
g.      Not thread-safe but can get thread-safe using Collections.synchronizedMap method at the cost of performace
h.      How hashmap works? http://www.journaldev.com/11560/java-hashmap
i.        Hashmap load factor: used to figure out when hash map will be rehashed and bucket size increased. By default, load factor=.75 and bucket/capapcity=16. Threshold=load factor* capacity=12. When there are more than 12 mapping bucket size increases to the next power of 2 i.e. 32. If we want to save space, we can increase load factor to .8/.9 but get and set operation will take more time.
j.        remove() remove the entry with this key

4.      TreeSet:

5.      HashSet: Implementation of Set Interface backed by HashMap.
a.      No guarantee for iteration order and permits null element.Doesn’t guarantee insertion order
b.      Not thread-safe but can get thread-safe using Collections.synchronizedSet method at the cost of performace.
c.       Supports Generics, to avoid ClassCastException at runtime
d.      Used HashMap for storing elements, so the object should have good implementation of hashCode() and equal() method to avoid unwanted results.

Java Collections API Algorithms
1.      Sorting
2.      Shuffling
3.      Searching
4.      Composition
5.      Min and Max values