Sunday, 18 September 2016

Learn javascript closures

What is a closure?
A closure is an inner function that has access to the outer (enclosing) function’s variables—scope chain. 
The closure has three scope chains: it has access to its own scope (variables defined between its curly brackets), it has access to the outer function’s variables, and it has access to the global variables.
The inner function has access not only to the outer function’s variables, but also to the outer function’s parameters. Note that the inner function cannot call the outer function’s arguments object, however, even though it can call the outer function’s parameters directly.
You create a closure by adding a function inside another function.
A Basic Example of Closures in JavaScript:
function showName (firstName, lastName) {

var nameIntro = "Your name is ";
// this inner function has access to the outer function's variables, including the parameter
function makeFullName () {

return nameIntro + firstName + " " + lastName;

}
return makeFullName ();

}

showName ("Michael", "Jackson"); // Your name is Michael Jackson
Closures’ Rules and Side Effects
  1. Closures have access to the outer function’s variable even after the outer function returns:
    One of the most important and ticklish features with closures is that the inner function still has access to the outer function’s variables even after the outer function has returned. Yep, you read that correctly. When functions in JavaScript execute, they use the same scope chain that was in effect when they were created. This means that even after the outer function has returned, the inner function still has access to the outer function’s variables. Therefore, you can call the inner function later in your program. This example demonstrates:
    function celebrityName (firstName) {
    var nameIntro = "This celebrity is ";
    // this inner function has access to the outer function's variables, including the parameter
    function lastName (theLastName) {
    return nameIntro + firstName + " " + theLastName;
    }
    return lastName;
    }
    var mjName = celebrityName ("Michael"); // At this juncture, the celebrityName outer function has returned.
    // The closure (lastName) is called here after the outer function has returned above
    // Yet, the closure still has access to the outer function's variables and parameter
    mjName ("Jackson"); // This celebrity is Michael Jackson
    source : http://javascriptissexy.com/understand-javascript-closures-with-ease/

Friday, 16 September 2016

Race condition in multithreading

"When more than one thread try to access same resource without synchronization causes race condition."

So we can solve race condition by using either synchronized block or synchronized method. When no two threads can access same resource at a time phenomenon is also called as mutual exclusion.

Example (Train ticket booking)-
Let's say there is only 1 ticket available in train, and two passengers are trying to book that ticket at same time without synchronization.
It might happen that both might end up booking up ticket, though only ticket was available, which is of course going to create problem.
But if synchronization was there only of them would have been able to book ticket.


Program to show that without synchronization problems will happen when  2 passengers try to book train ticket, dat too when only 1 ticket was available
class TicketBooking implements Runnable{
   int ticketsAvailable=1;
  
   public void run(){
         
          System.out.println("Waiting to book ticket for : "+Thread.currentThread().getName());
          if(ticketsAvailable>0){
                 System.out.println("Booking ticket for : "+Thread.currentThread().getName());
                
                 //Let's say system takes some time in booking ticket (here we have taken 1 second time)
                 try{
                       Thread.sleep(1000);
                 }catch(Exception e){}
                  
                 ticketsAvailable--;
                 System.out.println("Ticket BOOKED for : "+ Thread.currentThread().getName());
                 System.out.println("currently ticketsAvailable = "+ticketsAvailable);
          }
          else{
                 System.out.println("Ticket NOT BOOKED for : "+ Thread.currentThread().getName());
          }
         
         
   }
  
}
public class MyClass {
   public static void main(String args[])
   {
          TicketBooking obj=new TicketBooking();
         
          Thread thread1=new Thread(obj,"Passenger1 Thread");
          Thread thread2=new Thread(obj,"Passenger2 Thread");
         
          thread1.start();
          thread2.start();
         
   }
}
/*OUTPUT
Waiting to book ticket for : Passenger1 Thread
Waiting to book ticket for : Passenger2 Thread
Booking ticket for : Passenger1 Thread
Booking ticket for : Passenger2 Thread
Ticket BOOKED for : Passenger1 Thread
currently ticketsAvailable = 0
Ticket BOOKED for : Passenger2 Thread
currently ticketsAvailable = -1
*/
If we note the above program,
first Passenger1 Thread and Passenger2 Thread waited to book tickets.
Than, both threads tried to check the available ticket count and it was 1.
Both threads were able to book ticket.
And ultimately available ticket was reduced to -1, which is practically impossible, tickets count can never dip below 0.

Above problem can be solved using synchronization.

Volatile keyword in java

Java allows threads to access shared variables. As a rule, to ensure that shared variables are consistently updated, a thread should ensure that it has exclusive use of such variables by obtaining a lock that enforces mutual exclusion for those shared variables.

mutual exclusion (mutex) is a program object that prevents simultaneous access to a shared resource.

If a field is declared volatile, in that case the Java memory model ensures that all threads see a consistent value for the variable.


What could be impact of not using volatile keyword?

public class Singleton{
private static volatile Singleton _instance; //volatile variable 

public static Singleton getInstance(){

   if(_instance == null){
            synchronized(Singleton.class){
              if(_instance == null)
              _instance = new Singleton();
            }

   }
   return _instance;

}

If you look at the code carefully you will be able to figure out:
1) We are only creating instance one time
2) We are creating instance lazily at the time of the first request comes.

If we do not make the _instance variable volatile than the Thread which is creating instance of Singleton is not able to communicate other thread, that instance has been created until it comes out of the Singleton block, so if Thread A is creating Singleton instance and just after creation lost the CPU, all other thread will not be able to see value of _instance as not null and they will believe its still null.



  1. Java allows threads to access shared variables. As a rule, to ensure that shared variables are consistently updated, a thread should ensure that it has exclusive use of such variables by obtaining a lock that enforces mutual exclusion for those shared variables. We can ensure such behaviour by using volatile keyword.

  1. If a field is declared volatile, in that case the Java memory model ensures that all threads see a consistent value for the variable.

  1. Volatile can be used as a keyword against the variable, we cannot use volatile against method declaration.
volatile  void method2() //it’s illegal
volatile int i; //legal

  1. In certain cases, Volatile keyword can be used as an alternate to synchronization in java, as all threads always have access to latest updated value.

  1. Using volatile is better than synchronization, as synchronization needs to block whole method (if used in method declaration) or block (if synchronization block is used), while volatile needs not to block any piece of code.

  1. Not Cached in CPU- Volatile members are never cached in CPU by jvm, they are always read from main memory i.e. from stack where variable lives.
It is possible for multiple CPU’s to exist on machine, so it is possibility that thread might cache different values in different CPU’s for same variable, so it’s important that value is not cached in CPU and always read from main memory.

  1. Volatile keyword must be used in multithreading environment, there is no use of using volatile keyword in non multi threading environment, it may cost us unnecessary performance issue as volatile keyword is not cached in memory by jvm.

  1. A compile-time error will occur if a final variable is declared volatile.

volatile final int x = 0; //The field x can be either final or volatile, not both.


  1. If variable which has been declared volatile, is a reference to object it may point to null as well,
volatile Integer i=null;  //it’s allowed.


      
  1. Performance issue - As volatile keyword is not cached in CPU, it is always read from main memory, so in terms of performance it’s always expensive to use volatile keyword.