Sunday, 20 November 2016

AngularJS2

Basics -
I. AngularJS2 is framework to build heavy javaScript applications.
It is mainly used to create SPA(Single Page Application.)
AngularJS2 is completely independent of AngularJS framework.

SPA vs MPA (Multi Page Application)
In multi page app each time a request is submitted a new page is served by the server and rendered.
This approach is OK for simple applications.
           But in case of rich use interface page becomes complex and to be loaded with a lot of  data.
Generating complex pages on server and transferring them to client over internet and rendering them in browser takes time and degrades user experience.
           Introduction of AJAX  improved MPA by refreshing a part of page( not full page) but increased page complexity.
SPA is a evolution of MPA+AJAX pattern,where only shell page is generated on the server and  UI is rendered by browser javaScript Code. SPA requests markup (HTML) and data separately and renders page directly in browser. 
In SPA only a part of shell page changes instead whole page.
eg. Gmail is SPA


SPA Advantages :
1.Faster page loading
2.Improved user interface because data is loaded in the background from server.
3.No need to write code to render page on server.
4.decoupling of Front end and Back end Development
5.can use same back end code(Web development) for Mobile development.

SPA Disadvantages :
1.Heavy frameworks to be loaded in browsers
2.UI code is not compiled hence its harder to debug.
3.search engine optimization problems

II. Typescript is used to develop angularJS2 app.
     TypeScript is a super set of javaScript. (Any valid JavaScript code is TypeScript code).
     TypeScript = JavaScript + additional Features
      
    Why to use TypeScript instead of JavaScript?
     These additional features are --> (modules,classes,interfaces,access  modifiers, intellisense, compile Time checking)

III.Ang2 Architecture -
    Main parts of  ng2 are -
    1.Component  - View Part
    2.Directive
    3.Router
    4.Service       -Service Part
 Component - {} encapsulates template,data and behavior (properties and methods) of view. (Is a class)
Main Component is called as Root Component.
Root Component has many sub components which help to divide app into smaller parts.
Components are completely decoupled from DOM .
In JavaScript we first select DOM element and then modify it.
In Ang2 we bind DOM element with component.
    Eg. component class variable - DOM element
          Component class method - DOM event  

Service - {} A class, which holds non-view logic like Business logic, Data Access , Logging  etc.
Router -  {} For navigarion
Directive -{} which  modifies DOM (like Component)
Unlike Component, it does not have html markup for view. 
 

 

 

Wednesday, 16 November 2016

What happens (Steps) when an URL is requested from address bar in Browser.(Eg.www.facebook.com)

Steps-
Suppose we type www.facebook.com in address bar of browser.

Whenever we want to connect to "facebook", we want to reach to the server where google web service is hosted. Each host name (facebook.com) has IP associated with it.
Eg. Say www.facebook.com has IP of 74.125.236.65.
        If we type http://www.facebook.com or http://74.125.236.65 we expect facebook server to show homepage. But both addresses may not be same.
But in real scenario facebook has multiple servers at multiple locations to cater huge volume of request they get per second. Hence we should let facebook decide which server is best for my response. Hence using host name solves the problem of typing actual facebook server IP.
        
              DNS (Domain Name System) resolves the problem of mapping URL with IP.
  
  1. First browser checks DNS records in its own cache for IP of requested server.
  If not found ,
  2. Browser checks DNS records in OS cache for IP of requested server.
  if not found,
  It decides to contact ISP.
  3. A request is sent to DNS server, that has the database of IP address and Host Names.
      DNS server tries to identify IP address for queried hostname.(It searches in DNS hierarchy until topmost DNS server).If found the requested IP , It is returned. Otherwise server not found message is sent.
 4. Since browser knows IP of server to contacted, Now browser initiates a TCP connection with server.
 5. Browser assembles http request which consists of header and optional content. 
     Request header has below content -

    
Where,
GET - http request type (always GET)
Accept - http response type expected
User Agent - Browser details
Connection - Asks connection server to keep TCP connection established for response.
Host - Host Name
Cookie - sent server cookie for previous browser session. Cookie has map with KV for user and Facebook

6. Browser receives the response in return.




where,
OK - http response status.
Content Type
Connection -asks browser to keep TCP connection open
Content -length - No of bytes

7. Browser renders HTML content.
    HTML rendering is also done in phases.
    7.1 - First HTML bare bone structure.
    7.2 - Then sends multiple GET request to get resources like images, JavaScript files, CSS files for HTML rendering.
   Now these images will be stored in the browser cache, so that next time it does not have to send    GET request to server for HTML rendering resources.
     







































Tuesday, 8 November 2016

Multi Threading in Java

Thread is lightweight, faster way to achieve multitasking.
Thread is a separate path of execution.
Threads shares common memory area and saves memory used hence they are  faster.

Thread is a part of process.It is executed inside the process.There is context switching among threads.
So OS has multiple processes and  each process has multiple threads.


Multithreading is a process of  executing multiple threads simultaneously.
Advantages -
1.It does not block user because each thread is independent.
2.It helps to do multiple operations together.

Thread Life Cycle -
There are 4 states-
1.New
2.Runnable
   Running (Optional)
3.Non-Runnable
4.Terminated 

 
 New -State when instance of thread Class is created but start() is not invoked.
 Runnable - State after start() invoked but Thread scheduler has not picked it for running.
 Running - State when Thread scheduler picked it for running.
 Non-Runnable - State when Thread is alive but not running.(Maybe blocked)
 Terminated - State when Thread is dead bacause run() exists.

How to create Thread -
1.extending Thread Class
2.implementing Runnable Interface
             1.Thread Class -
                                      1.1 - Thread()
                                      1.2 - Thread(String name)
                                      And override run()
             2.Runnable Interface -

                                      2.1 - Thread(Runnable r)
                                      2.2 - Thread(Runnable r,String name)
                                      And  implement run()
                                    
Thread Scheduler -
            It is a part of JVM which decides which runnable thread to run.
There is no guarantee that which thread will be picked by Scheduler to run.
 Only 1 Thread is executed at a time in single Process.

eg.
    Thread  t1 = new Thread();
    Thread  t1 = new Thread();  
//override run()

t1.start()  -> JVM calls run()
t2.start()  -> JVM calls run()

 How to run 2 Threads to print numbers?
void run(){
for(int i=1;i<5;i++)
try {
 Thread.sleep(500);   // sleep for 0.5 sec then go to syso

syso(i + Thread.getCurrentThread.getName());
}
o/p ->1 Thread 0   //for t1
          1 Thread 1   //for t2
          2 Thread 0
          2 Thread 1  
          3 Thread 0 
          3 Thread 1  
          4 Thread 0 
          4 Thread 1      

 What happens if w directly call run() on thread?

    Consider above eg.
    t1.run();
    t2.run();
Directly calling run method does not create Thread Object But Create Normal Object.

o/p-> 1 main    
          2 main
          3 main
          4 main
          1 main
          2 main
          3 main
          4 main
          
Its like running same method twice. 

Can we call same thread Twice?
t1.start();
t1.start();

No.It will throw IllegalThread Runtime Exception.
 
 join() - used to let current thread execute till it dies. Then Executes next Thread.
t1.start();
t1.join() //called join()
t2.start(); 
t3.start(); 
o/p - 1Thread 0
         2Thread 0
         3Thread 0
         4Thread 0  //till t1 finishes
         1Thread 1  //t2
         1Thread 2  //t3
         2Thread 1
         2Thread 2
         3Thread 1
         3Thread 2
         4Thread 1
         4Thread 2          

 
Priority Of Thread -
To set Priority Of Thread -
MIN_PRIORITY        value is 1
NORM_PRIORITY    value is 5
MAX_PRIORITY       value is 10
 eg.
t2.setPriority(MIN_PRIORITY);
t1.setPriority(MAX_PRIORITY);

t1.start();
t2.start();
//Now Thread with Max Priority will be executed first by JVM.
But it always not guaranteed.

Imp Methods -
1.sleep() - makes the thread sleep for  specified time.(Thread changes from running to runnable)
2.yield() - makes the current running thread to allow other threads with same priority to run in same Thread pool.
Eg.  If T Thread pool has total 5 Threads and  T1 ,T2 with same priority of 10.
It we call
t1.start()
t4.start()
t5.start()
t3.start()
t2.start()

Then , while T1 is running it allows T2 also to run because of same Priority in the same pool.
3.Join() - makes the thread complete run() before allowing next Thread to run.
 

Java Exception Handlling

Exception Handling -
It is the mechanism to handle the runtime errors so that the normal flow of application is maintained.

2 types of exceptions -
1.Checked
2.Unchecked

 Checked Exceptions- checked at the compile time and they must be catched (using catch block).
 All sub-exceptions of Exception class except Runtime Exception are checked exception.
  eg. IOException
        SQLException
        ClassNotFoundException

Unchecked Exception- Checked at the runtime.
eg. ArithmeticException
     NullPointerException
    ArrayOutOfBoundException

How to handle?
 1.try-catch
 2.try-finally
 3.try-multiple catch  -
    Only one catch is executed.
    Exceptions must in order of specific to generic in case of multiple catch use.
    Only 1 finally loop can be used.
  4.throws keyword(both checked and unchecked)

Exception Propagation-
Unchecked -> Automatically propagates from current method to previous method and so on until it is catched.
Checked  -> Automatically does not propagate.
                      Must be handled by using throws method signature. 
link->http://www.javatpoint.com/exception-propagation

Throws only declare exception but for smooth flow it must be handled.
              1.Declare Throws -> and Exception Occurs -> It will throw exception at runtime.
              2.Declare Throws -> and Handle Exception with try-catch               




Monday, 7 November 2016

Java Strings

Java String is Immutable.
String Builder and String Buffer are not Immutable.
Other Immutable Classes -
All Wrapper class like Integer, Long,Short,Byte,Double,Long ,Char etc.


Advantage of being Immutable-
1.Immutable classes are inherently thread safe. No worry in Multi threaded environment.
2.Security Reasons - Database URL , username and password are String.If they can be altered it the  problem in app security.
  
How to create Immutable Class ->
1.Declare class Final so that class can not be overridden.
2.Make all fields Private so that direct access not allowed.
3.Do not provide setter method
4.Make all fields Final so that their value can be assigned only once.
5.Initialize all fields in constructor using deep copy.

String Object Creation -
1.Using Literal --> "abc" - creates 1Obj and 1 reference - stored in String Pool
2.Using new --> new String("abc")  - creates 2Obj and 1 reference - each stored in Pool and Heap
3.Using concatenation -
 
String Concatenation -
1.Using + operator
2.Using concat()
          + Operator - compiler uses StringBuilder to add Strings using append()
                          eg. String s = "Tushar"+"Patil"
             Compiler internally handles as below -

             String s=(new StringBuilder()).append("Sachin").append(" Tendulkar).toString();
            Also,
            In Concatenation once String Literal occurs all next + are considers as concat.
                         eg. String s = 30+40+"Tushar"+50+30;
                              Ans-> s = 70Tushar5030.
 Concat and +Operator creates new Object as seen in above.
 Hence == with same literal is always false.  
Eg. String s1 = "abc";
       String s2 = "a";
       String s3 ="bc";
       String s4 = s2+s3;
       Now- s1==  s4  -> False. (Becauase + creates new Object of string at compilation)
           

Wednesday, 2 November 2016

Class Loader in Java

Java ClassLoaders are used to load classes at runtime.
Java ClassLoaders  work on 3 main principles.

1.Delegation
2.Visibility
3.Uniqueness

Delegation forwards the request of  class loading to Parent Class Loader and only loads the class when Parent ClassLoader is not able to find or load the Class.

Visibility helps child loader to see the classes loaded by Parent Class.

Uniqueness allows any class to load exactly once.
This is achieved by the help of Delegation.
It ensures that child ClassLoader does not load the class which have been already loaded by Parent ClassLoader.

What is Class Loader in Java?
ClassLoader is a class which is used to load class files. Java compiler javac compiles java files into class files. Then JVM executes byte code in class files. ClassLoaders are responsible for loading classes from System or Network.

Default Functioning of ClassLoader -
A ClassLoader's basic purpose is to service a request for a class. The JVM needs a class, so it asks the ClassLoader, by name, for this class, and the ClassLoader attempts to return a Class object that represents the class.

 There are 3 default ClassLoaders in Java

1.BootStrap  ClassLoader
2.Extension  ClassLoader
3.System ClassLoader

Every ClassLoader has predefined function from where they loads the classes.
Bootstrap ClassLoader is responsible for loading standard JDK class files from rt.jar
It is the Parent of all ClassLoaders.
(*note - rt.jar file is present in jre/bin)

Extension ClassLoader delegates loading request to Bootstrap, if unsuccessful loads classes from
dir jre/bin/ext .

System ClassLoader is responsible to load classes from classpath or -cp command line option or
Class-Path attribute inside JAR
  
Except Bootstrap all class Loaders are implemented by java.lang.classLoader.
Bootstrap is implemented in C.