Tuesday 30 December 2014

GIT COMMANDS

Git is a distributed version control system with an emphasis on speed, data integrity and support for distributed and non linear work flows.

Below are some of the popular commands:


git status   # changed file in your working directory

git add .   #Add all changes to the next commit

git diff    #changes to tracked files

git branch <new branch>  # create a new branch based on your current head

git branch -d <branch>  #Delete a local branch

git pull --all

git log

git branch   # list all the existing branch

git stash

     git stash apply     # apply last stashed changes to working dir

     git stash list          # see your stashed changes

     git stash apply stash@{2}    # apply specific stashed changes.

git remote show origin          #to see the repository url


git reset HEAD^                  # remove commit locally
git push origin +HEAD       # force-push the new HEAD commit

Thursday 30 October 2014

SPRING BATCH

Spring Batch, is an open source framework for batch processing – execution of a series of jobs. Spring Batch provides classes and APIs to read/write resources, transaction management, job processing statistics, job restart and partitioning techniques to process high-volume of data.


Spring Batch is a framework for batch processing – execution of a series of jobs. In Spring Batch, A job consists of many steps and each step consists of a READ-PROCESS-WRITE task or single operation task (tasklet).
  1. For “READ-PROCESS-WRITE” process, it means “read” data from the resources (csv, xml or database), “process” it and “write” it to other resources (csv, xml and database). For example, a step may read data from a CSV file, process it and write it into the database. Spring Batch provides many made Classes to read/write CSV, XML and database.
  2. For “single” operation task (tasklet), it means doing single task only, like clean up the resources after or before a step is started or completed.
  3. And the steps can be chained together to run as a job.
1 Job = Many Steps.
1 Step = 1 READ-PROCESS-WRITE or 1 Tasklet.
Job = {Step 1 -> Step 2 -> Step 3} (Chained together)

Spring Batch Examples

Consider following batch jobs :
  1. Step 1 – Read CSV files from folder A, process, write it to folder B. “READ-PROCESS-WRITE”
  2. Step 2 – Read CSV files from folder B, process, write it to the database. “READ-PROCESS-WRITE”
  3. Step 3 – Delete the CSB files from folder B. “Tasklet”
  4. Step 4 – Read data from a database, process and generate statistic report in XML format, write it to folder C. “READ-PROCESS-WRITE”
  5. Step 5 – Read the report and send it to manager email. “Tasklet”
In Spring Batch, we can declare like the following :


  <job id="abcJob" xmlns="http://www.springframework.org/schema/batch">
 <step id="step1" next="step2">
   <tasklet>
  <chunk reader="cvsItemReader" writer="cvsItemWriter"  
                    processor="itemProcesser" commit-interval="1" />
   </tasklet>
 </step>
 <step id="step2" next="step3">
   <tasklet>
  <chunk reader="cvsItemReader" writer="databaseItemWriter"  
                    processor="itemProcesser" commit-interval="1" />
   </tasklet>
 </step>
 <step id="step3" next="step4">
   <tasklet ref="fileDeletingTasklet" />
 </step>
 <step id="step4" next="step5">
   <tasklet>
  <chunk reader="databaseItemReader" writer="xmlItemWriter"  
                    processor="itemProcesser" commit-interval="1" />
   </tasklet>
 </step>
 <step id="step5">
  <tasklet ref="sendingEmailTasklet" />
 </step>
  </job>
The entire jobs and steps execution are stored in database, which make the failed step is able to restart at where it was failed, no need start over the entire job.

Monday 20 October 2014

REST - Representational State Transfer

Monday 8 September 2014

JSON vs XML

JSON JavaScript Object Notation
XML Extensive Markup Language

Following are key differences between JSON & XML, which will help to decide which content format one should use in there application :


  • Parsing and Generating JSON data is easier as compared to XML.
  • JSON has simpler structure than XML.
  •  In XML document manipulation is easy as compared to JSON.You can easily find/update nodes.You have XPath/XQuery for XML, Do we have it for JSON ? 
  • You can do lots of thing with XML for example converting XML to HTML using XLST, such tools not available for JSON.
  •  XML is more rich in features and you can have more control over data and do great amount of validation as compared to JSON.You can have DTD's for XML to specify validation in details 
  • Working with JSON is simpler, especially with Javascript, just by giving call to Eval will give you Javascript Object.
  • JSON is not in a document format neither it is markup language but XML is.
  • JSON has great language support as compared to XML.
  • JSON is best for simpler use/scenario, for better security,support and validation XML is better.

  • JSON is faster as compared to XML as it is less rich, there is less overhead of tags & there is simpler validation rules.    

REST vs SOAP

REST stands for REpresentational State Transfer (REST) which enforces a stateless client server design where web services are treated as resource and can be accessed and identified by there URL unlike SOAP web services which were defined by WSDL.
Web services written by applying REST Architectural concept are called RESTful web services which focus on System resources and how state of Resource should be transferred over http protocol.

SOAP
SOAP, originally defined as Simple Object Access Protocol, is a protocol specification for exchanging structured information in XML form.SOAP is protocol which relies on XML, that defines what is in the message and how to process it,set of encoding rules for data types, representation for procedure calls and responses.


REST vs SOAP

Before going for differences between two lets first see the differences in request header :

Sample SOAP & REST Request message for Weather Web Service :






 


SOAP vs REST Key Differences
Here are some of Key differences between SOAP and REST web Service :

  •  REST uses HTTP/HTTPS, SOAP can use almost any transport to send the request(for example we can have SOAP Messages over SMTP),  SOAP is a XML based messaging protocol.
  • REST is totally stateless operations where as SOAP supports statefull calls too. 
  • SOAP has more strict contract in the form of WSDL between applications, no such contract exists in case of REST.
  • AS REST APIs can be consumed using simple GET requests, REST response can be cached, this is not possible with SOAP.
  • REST is Lighter, SOAP requires an XML wrapper around every request and response(SOAP Headers, XML tags etc). Thats why REST is preferred choice in mobile devices and PDA's
  •  SOAP message format is restricted to XML only where as REST supports other formats too for example JSON.  
  • REST is simpler in terms of development as compared to SOAP.
  • Browsers can handle REST easily as compared to SOAP as REST is based on HTTP where SOAP is another wrapper over HTTP.

Why to use SOAP ?
SOAP provides some features like Security, Reliable Messaging, Atomic transaction which are not available in REST API.

  • WS-Security  & WS-SecureConversation  Provide support for using security tokens like Kerberos, and X.509.
  • WS-ReliableMessaging   Reliable messages delivery between distributed applications in case of failures.
  • WS-AtomicTransaction, two-phase commit across distributed transactional resources
  • In case where exact specification  of exchange format need to agreed between applications SOAP is better suitable.

Sunday 7 September 2014

Internal implementation of Set/HashSet (How Set Ensures Uniqueness)

Set Implementation Internally in Java

Each and every element in the set is unique .  So that there is no duplicate element in set .

 what happens internally when you pass duplicate elements in the  add() method of the Set object , It will return false and do not add to the HashSet , as the element is already present .So far so good .

But the main problem arises that how it returns false . So here is the answer

When you open the HashSet implementation of the add() method in Java Apis that is rt.jar , you will find the following code in it



public class HashSet<E>
extends AbstractSet<E>
implements Set<E>, Cloneable, java.io.Serializable

{
    private transient HashMap<E,Object> map;
    
    // Dummy value to associate with an Object in the backing Map
    
    private static final Object PRESENT = new Object();
    
    
    
    public HashSet() {
        map = new HashMap<>();
    }
    
    // SOME CODE ,i.e Other methods in Hash Set
    
    
    public boolean add(E e) {
        return map.put(e, PRESENT)==null;
    }
    
    
    
    // SOME CODE ,i.e Other methods in Hash Set
}


So , we are achieving uniqueness in Set,internally in java  through HashMap . Whenever you create an object of HashSet it will create an object of HashMap as you can see in the italic lines in the above code .

The main point to notice in above code is that put (key,value) will return

1.  null , if key is unique and added to the map
2.  Old Value of the key , if key is duplicate

So , in HashSet add() method ,  we check the return value of map.put(key,value) method with null value
i.e.

   public boolean add(E e) {
            return map.put(e, PRESENT)==null;
       }

So , if map.put(key,value) returns null ,then
map.put(e, PRESENT)==null      will return true and element is added to the HashSet .



So , if map.put(key,value) returns old value of the key ,then
map.put(e, PRESENT)==null      will return false and element is  not added to the HashSet .

Friday 5 September 2014

instanceOf comparison


class Tree {

}

class Pine extends Tree{

}

class Oak extends Tree{

}

class TestTree{
    public static void main (String args[]){
        Tree t = new Pine();
        System.out.println(t instanceof Pine);  // returns true
        System.out.println(t instanceof Tree);  // returns true
        System.out.println(t instanceof Oak);   // returns false
        System.out.println(t instanceof Object);   // returns true

        Tree tree = new Tree();
        System.out.println(tree instanceof Pine);  // returns false
        System.out.println(tree instanceof Tree);  // returns true
        System.out.println(tree instanceof Oak);   // returns false
        System.out.println(tree instanceof Object);   // returns true
    }
}

Primitive Data Types

The Java programming language is statically-typed, which means that all variables must first be declared before they can be used. 


A primitive type is predefined by the language and is named by a reserved keyword. Primitive values do not share state with other primitive values. The eight primitive data types supported by the Java programming language are:

  • byte: The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive). The byte data type can be useful for saving memory in large arrays, where the memory savings actually matters. They can also be used in place of int where their limits help to clarify your code; the fact that a variable's range is limited can serve as a form of documentation.
  • short: The short data type is a 16-bit signed two's complement integer. It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive). As with byte, the same guidelines apply: you can use a short to save memory in large arrays, in situations where the memory savings actually matters.
  • int: By default, the int data type is a 32-bit signed two's complement integer, which has a minimum value of -231 and a maximum value of 231-1. In Java SE 8 and later, you can use theint data type to represent an unsigned 32-bit integer, which has a minimum value of 0 and a maximum value of 232-1. Use the Integer class to use int data type as an unsigned integer. See the section The Number Classes for more information. Static methods like compareUnsigned, divideUnsigned etc have been added to the Integer class to support the arithmetic operations for unsigned integers.
  • long: The long data type is a 64-bit two's complement integer. The signed long has a minimum value of -263 and a maximum value of 263-1. In Java SE 8 and later, you can use the longdata type to represent an unsigned 64-bit long, which has a minimum value of 0 and a maximum value of 264-1. Use this data type when you need a range of values wider than those provided by int. The Long class also contains methods like compareUnsigned, divideUnsigned etc to support arithmetic operations for unsigned long.
  • float: The float data type is a single-precision 32-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in the Floating-Point Types, Formats, and Values section of the Java Language Specification. As with the recommendations for byte and short, use a float (instead of double) if you need to save memory in large arrays of floating point numbers. This data type should never be used for precise values, such as currency. For that, you will need to use the java.math.BigDecimal class instead.Numbers and Strings covers BigDecimal and other useful classes provided by the Java platform.
  • double: The double data type is a double-precision 64-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in the Floating-Point Types, Formats, and Values section of the Java Language Specification. For decimal values, this data type is generally the default choice. As mentioned above, this data type should never be used for precise values, such as currency.
  • boolean: The boolean data type has only two possible values: true and false. Use this data type for simple flags that track true/false conditions. This data type represents one bit of information, but its "size" isn't something that's precisely defined.
  • char: The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).

    The following chart summarizes the default values for the above data types.
    Data TypeDefault Value (for fields)
    byte0
    short0
    int0
    long0L
    float0.0f
    double0.0d
    char'\u0000'
    String (or any object)  null
    booleanfalse

Common Observations:

       final int i =100;
        byte b = i;
        System.out.println(b);  // valid prints 100


        /*
        final int x =1000;
        byte y = x;   //compile error
        System.out.println(y);  */


        /*
         int x =100;
        byte y = (byte) x;   //valid
        System.out.println(y); */


        /*int x =100;
        byte y =  x;   //compile error. Nee to cast x --  byte y =  (byte) x
        System.out.println(y); */

        char c = 9;   //valid
        char d = 'A';  //valid
        char e = 0x12; //valid

        int j = 0345;  //valid
   
        System.out.println(1+2f+3d); // print 6.0

        /*final long test = 1;
        byte b1 = test; //compile error
        System.out.println(b1);*/
 

OverLoading vs Overriding



Method overloading and method overriding in Java is two important concept in Java which allows Java programmer to declare method with same name but different behaviour. Method overloading and method overriding is based on polymorphism in Java. 

In case of method overloading, method with same name co-exists in same class but they must have different method signature, while in case of method overriding, method with same name is declared in derived class or sub class.Method overloading is resolved using static binding in Java at compile time while method overriding is resolved using dynamic binding in Java at runtime. In short When you overload a method in Java its method signature got changed while in case of overriding method signature remains same but a method can only be overridden in sub class

OverLoad:
If you have two methods with same name in one Java class with different method signature than its called overloaded method in Java. Generally overloaded method in Java has different set of arguments to perform something based on different number of input. You can also overload constructor in Java, which we will see in following example of method overloading in Java. Binding of overloading method occurs during compile time and overloaded calls resolved using static binding. To overload a Java method just changes its signature. Just remember in order to change signature you either need to change number of argument, type of argument or order of argument in Java if they are of different types. Since return type is not part of method signature simply changing return type will result in duplicate method and you will get compile time error in Java.

 Remember you can overload static method in Java, you can also overload private and final method in Java but you can not override them.

You can overload the main() method, but only public static void main(String[] args) will be used when your class is launched by the JVM.


Override:
In order to override a Java method, you need to create a child class which extends parent. Overridden method in Java also shares same name as original method in Java but can only be overridden in sub class. Original method has to be defined inside interface or base class, which can be abstract as well. When you override a method in Java its signature remains exactly same including return type. JVM resolves correct overridden method based upon object at run-time by using dynamic binding in Java.

Rule of Method Override
  1. Method signature must be same including return type, number of method parameters, type of parameters and order of parameters
  2. Overriding method can not throw higher Exception than original or overridden method. means if original method throws IOException than overriding method can not throw super class of IOException e.g. Exception but it can throw any sub class of IOException or simply does not throw any Exception. This rule only applies to checked Exception in Java, overridden method is free to throw any unchecked Exception.
  3. Overriding method can not reduce accessibility of overridden method , means if original or overridden method is public than overriding method can not make it protected.

Summary
  1. First and most important difference between method overloading and overriding is that, In case of method overloading in Java, Signature of method changes while in case of method overriding it remain same.
  2.  Second major difference between method overloading vs overriding in Java is that You can overload method in one class but overriding can only be done on subclass.
  3. You can not override static, final and private method in Java but you can overload static, final or private method in Java.
  4. Overloaded method in Java is bonded by static binding and overridden methods are subject to dynamic binding.

Wednesday 3 September 2014

Application Server vs Web Server

1. Application Server supports distributed transaction and EJB. While Web Server only supports Servlets and JSP.

2. Application Server can contain web server in them. most of App server e.g. JBoss or WAS has Servlet and JSP container.

3. Though its not limited to Application Server but they used to provide services like Connection pooling, Transaction management, messaging, clustering, load balancing and persistence. Now Apache tomcat also provides connection pooling.

4. In terms of logical difference between web server and application server. web server is supposed to provide http protocol level service while application server provides support to web service and expose business level service e.g. EJB.

5. Application server are more heavy than web server in terms of resource utilization.


Sunday 31 August 2014

JDK 8 Features

Lambda Expressions

The biggest new feature of Java 8 is language level support for lambda expressions.

The point of lambda is to be able to pass some code to a method rather than objects. Until java 8, the way to achieve this in java would be to use callbacks. The issue with callbacks is that it leads to verbose code. Like you would write 5 lines of code when the real job is in 1 of these 5 lines.

The other scenario is when dealing with group of data to execute specific algorithm on it.
Here are few code examples of lambda expressions usage.

Inner classes

An example of what you would do today:
btn.setOnAction(new EventHandler<ActionEvent>() {
    @Override
    public void handle(ActionEvent event) {
        System.out.println("Hello World!");
    }
});
With lambda in java 8 you just have:
btn.setOnAction(
    event -> System.out.println("Hello World!")
);

Method references

Two examples with static and non statics methods.
Statics method:
public class Utils {
    public static int compareByLength(String in, String out){
        return in.length() - out.length();
    }
}

public class MyClass {
    public void doSomething() {
        String[] args = new String[] {"microsoft","apple","linux","oracle"}
        Arrays.sort(args, Utils::compareByLength);
    } 
}
Non statics method:
public class MyClass implements Comparable<MyObject> {
    
    @Override
    public int compareTo(MyObject obj) {return ...}

    public void doSomething() {
        MyObject myObject = new MyObject();
        Arrays.sort(args, myObject::compareTo);
    } 
}

Date/Time changes

The Date/Time API is moved to java.time package and Joda time format is followed. Another goodie is that most classes are Threadsafe and immutable.

Stream Collection Types (java.util.stream)

A stream is a iterator that allows a single run over the collection it is called on. You can use streams to perform functional operations like filer or map/reduce over collections which can be streamed as individual elements using Stream objects. Streams can run sequentially or parallely as desired. The parallel mode makes use of fork/join framework and can leverage power of multiple cores.

Other – (nice to have) Changes

String.join() method is a welcome addition as a lot of self created utility classes are created instead. So, the following example

String abc= String.join(" ", "Java", "8");
Will get evaluated as “Java 8″.

Annotation on Java Types

Base64 Encoding/Decoding


Defines a standard API for BASE64 Encoding and Decoding
java.util.Base64.Encoder
java.util.Base64.Decoder

This feature means we don’t have to search around for other implementations, making things a bit easier.

Encoding

String base64 = Base64.getEncoder().encodeToString("string to encode".getBytes("utf-8"));

Decoding

byte[] asBytes = Base64.getDecoder().decode("your base 64 string");

Functional interfaces

A functional interface is the one that defines exactly one abstract method. We have for instance “java.lang.Runnable” defining the run abstract method:
public abstract void run();
We can still add as many default methods (non abstract) as we like.
While defining a new functional interface, we will have to define the new annotation “@FunctionalInterface”. This will allow us to block bad usages of functional interfaces as it will not compile if used improperly with the new annotation.

Remove the Permanent Generation

That is definitely a big one. The Permanent Generation (PermGen) space has completely been removed and is kind of replaced by a new space called Metaspace.
The consequences of the PermGen removal is that obviously the PermSize and MaxPermSize JVM arguments are ignored and you will never get a java.lang.OutOfMemoryError: PermGen error.
However that doesn't mean you won't have to worry about the class metadata memory footprint and it does not eliminate class and classloader memory leaks.

Most allocations for the class metadata are now allocated out of native memory and classes used for describing the class metadata are removed. The Metaspace will dynamically re-size depending on the application demand at runtime. There is obviously some garbage collection involved but I don't think that there is much to worry about here unless you have a problem of classes, classloaders memory leak or an inadequate sizing of the metaspace (as you can specify the maximum metaspace capacity with MaxMetaspaceSize otherwise it is limited by the amount of available native memory).

Small VM


The goal here is to have a VM which is no more than 3Mb by allowing some features to be excluded at build time. The motivation behind this is to allow the JVM to run on small devices which have very strict static and dynamic memory-footprint requirements.

Parallel array sorting

Java 8 introduces a new API for sorting: Arrays#parallelSort.

Arrays#parallelSort uses Fork/Join framework introduced in Java 7 to assign the sorting tasks to multiple threads available in the thread pool.



References:
https://leanpub.com/whatsnewinjava8/read
http://java.dzone.com/articles/java-8-permgen-metaspace
http://java.dzone.com/articles/introduction-functional-1

JDK 7 Features

switch on String

Before JDK 7, only integral types can be used as selector for switch-case statement. In JDK 7, you can use a String object as the selector. For example,

String day = "SAT";
switch (day) {
   case "MON": System.out.println("Monday"); break;
   case "TUE": System.out.println("Tuesday"); break;
   case "WED": System.out.println("Wednesday"); break;
   case "THU": System.out.println("Thursday"); break;
   case "FRI": System.out.println("Friday"); break;
   case "SAT": System.out.println("Saturday"); break;
   case "SUN": System.out.println("Sunday"); break;
   default: System.out.println("Invalid");
}

String.equals() method is used in comparison, which is case-sensitive.

Binary Literals with prefix "0b"

In JDK 7, you can express literal values in binary with prefix '0b' (or '0B') for integral types (byte, short, int and long), similar to C/C++ language. Before JDK 7, you can only use octal values (with prefix '0') or hexadecimal values (with prefix '0x' or '0X').

BEFORE:

public void testBinaryIntegralLiterals(){
 
        int binary = 8;
 
        if (binary == 8){
            System.out.println(true);
        } else{
            System.out.println(false);
        }
}

AFTER:

public void testBinaryIntegralLiterals(){
 
        int binary = 0b1000; //2^3 = 8
 
        if (binary == 8){
            System.out.println(true);
        } else{
            System.out.println(false);
        }
}

Underscore for Numeric Literals

In JDK 7, you could insert underscore(s) '_' in between the digits in an numeric literals (integral and floating-point literals) to improve readability. For example,

int anInt = 0b10101000_01010001_01101000_01010001;
double aDouble = 3.1415_9265;
float  aFloat = 3.14_15_92_65f;

Catching Multiple Exception Types

In JDK 7, a single catch block can handle more than one exception types. For example, before JDK 7, you need two catch blocks to catch two exception types although both perform identical task:
try {
   ......
} catch(ClassNotFoundException ex) {
   ex.printStackTrace();
} catch(SQLException ex) {
   ex.printStackTrace();
}
In JDK 7, you could use one single catch block, with exception types separated by '|'.
try {
   ......
} catch(ClassNotFoundException|SQLException ex) {
   ex.printStackTrace();
}

The try-with-resources Statement a.k.a Automatic Resource Management

For example, before JDK 7, we need to use a finally block, to ensure that a resource is closed regardless of whether the try statement completes normally or abruptly. The code is messy!
import java.io.*;
// Copy from one file to another file character by character.
// Pre-JDK 7 requires you to close the resources using a finally block.
public class FileCopyPreJDK7 {
   public static void main(String[] args) {
      BufferedReader in = null;
      BufferedWriter out = null;
      try {
         in  = new BufferedReader(new FileReader("in.txt"));
         out = new BufferedWriter(new FileWriter("out.txt"));
         int charRead;
         while ((charRead = in.read()) != -1) {
            System.out.printf("%c ", (char)charRead);
            out.write(charRead);
         }
      } catch (IOException ex) {
         ex.printStackTrace();
      } finally {            // always close the streams
         try {
            if (in != null) in.close();
            if (out != null) out.close();
         } catch (IOException ex) {
            ex.printStackTrace();
         }
      }
 
      try {
         in.read();   // Trigger IOException: Stream closed
      } catch (IOException ex) {
         ex.printStackTrace();
      }
   }
}
JDK 7 introduces a try-with-resources statement, which ensures that each of the resources in try(resources) is closed at the end of the statement. This results in cleaner codes.
import java.io.*;
// Copy from one file to another file character by character.
// JDK 7 has a try-with-resources statement, which ensures that
// each resource opened in try() is closed at the end of the statement.
public class FileCopyJDK7 {
   public static void main(String[] args) {
      try (BufferedReader in  = new BufferedReader(new FileReader("in.txt"));
           BufferedWriter out = new BufferedWriter(new FileWriter("out.txt"))) {
         int charRead;
         while ((charRead = in.read()) != -1) {
            System.out.printf("%c ", (char)charRead);
            out.write(charRead);
         }
      } catch (IOException ex) {
         ex.printStackTrace();
      }
   }
}

Type Inference for Generic Instance Creation

import java.util.*;
public class JDK7GenericTest {
   public static void main(String[] args) {
      // Pre-JDK 7
      List<String> lst1 = new ArrayList<String>();
      // JDK 7 supports limited type inference for generic instance creation
      List<String> lst2 = new ArrayList<>();
 
      lst1.add("Mon");
      lst1.add("Tue");
      lst2.add("Wed");
      lst2.add("Thu");
 
      for (String item: lst1) {
         System.out.println(item);
      }
 
      for (String item: lst2) {
         System.out.println(item);
      }
   }
}

Fork Join framework in Java 7


Fork join framework exists even before Java 7 but as a separate JSR. It has been added as new feature in Java 7 to make it part of standard Java 7 core library. Fork join framework allows you to write code which can take advantage of multiple cores present in modern servers. 

Fork-join functionality is achieved by ForkjoinTask object, it has two method fork() and join () Method.
  • The fork() method allows  a new ForkJoinTask to be launched from an existing one.
  • The join() method allows a ForkJoinTask to wait for the completion of another one.
Again ForkjoinTask object has been of two types: RecursiveAction and RecursiveTask which is more specialized form of this instance. While RecursiveAction represent executions that do not yield a return value, Instances of RecursiveTask yield return values.

Thread vs Process in Java

1) Both process and Thread are independent path of execution but one process can have multiple Threads.
2) Every process has its own memory space, executable code and a unique process identifier (PID) while every thread has its own stack in Java but it uses process main memory and share it with other threads.
3) Threads are also refereed as task or light weight process (LWP) in operating system
4) Threads from same process can communicate with each other by using Programming language construct like wait and notify in Java and much simpler than inter process communication.
5) Another difference between Process and Thread in Java is that it's How Thread and process are created. It's easy to create Thread as compared to Process which requires duplication of parent process.
6) All Threads which is part of same process share system resource like file descriptors , Heap Memory and other resource but each Thread has its own Exception handler and own stack in Java.

There were some of the fundamental difference between Process and Thread in Java. Whenever you talk about Process vs Thread, just keep in mind that one process can spawn multiple Thread and share same memory in Java. Each thread has its own stack.

Some linux command map Java thread with light weight process or lwp, e.g. if you use prstat command in Solaris, you can get how many light weight process or Thread a particular Java program is using.

Why wait, notify and notifyAll is defined in Object Class and not on Thread class in Java

1) Wait and notify is not just normal methods or synchronization utility, more than that they are communication mechanism between two threads in Java. And Object class is correct place to make them available for every object if this mechanism is not available via any java keyword like synchronized. Remember synchronized and wait notify are two different area and don’t confuse that they are same or related. Synchronized is to provide mutual exclusion and ensuring thread safety of Java class like race condition while wait and notify are communication mechanism between two thread.

2 )Locks are made available on per Object basis, which is another reason wait and notify is declared in Object class rather then Thread class.

3) In Java in order to enter critical section of code, Threads needs lock and they wait for lock, they don't know which threads holds lock instead they just know the lock is hold by some thread and they should wait for lock instead of knowing which thread is inside the synchronized block and asking them to release lock. this analogy fits with wait and notify being on object class rather than thread in Java.


Synchronization, Synchroinzed Block, Method, locking and Threadsafety in Java

Multithreading and synchronization is a very important topic for any Java programmer.

Synchronization in Java

Synchronization in Java is possible by using Java keywords "synchronized" and "volatile”. Concurrent access of shared objects in Java introduces to kind of errors: thread interference and memory consistency errors and to avoid these errors you need to properly synchronize your Java object to allow mutual exclusive access of critical section to two threads.

Need of Synchronization

If your code is executing in multi-threaded environment, you need synchronization for objects, which are shared among multiple threads, to avoid any corruption of state or any kind of unexpected behaviour. Synchronization in Java will only be needed if shared object is mutable. if your shared object is either read only or immutable object, than you don't need synchronization, despite running multiple threads.
if all the threads are only reading value then you don't require synchronization in Java. JVM guarantees that Java synchronized code will only be executed by one thread at a time.
  1. synchronized keyword in Java provides locking, which ensures mutual exclusive access of shared resource and prevent data race.
  2. synchronized keyword also prevent reordering of code statement by compiler which can cause subtle concurrent issue if we don't use synchronized or volatile keyword
  3. synchronized keyword involve locking and unlocking. before entering into synchronized method or block thread needs to acquire the lock, at this point it reads data from main memory than cache and when it release the lock, it flushes write operation into main memory which eliminates memory inconsistency errors.
You can have both static synchronized method and non static synchronized method and synchronized blocks in Java but we can not have synchronized variable in java

Using synchronized keyword with variable is illegal and will result in compilation error. Instead of synchronized variable in Java, you can have java volatile variable, which will instruct JVM threads to read value of volatile variable from main memory and don’t cache it locally. 

Block synchronization in Java is preferred over method synchronization in Java because by using block synchronization, you only need to lock the critical section of code instead of whole method. Since synchronization in Java comes with cost of performance, we need to synchronize only part of code which absolutely needs to be synchronized.

Important points

1. Synchronized keyword in Java is used to provide mutual exclusive access of a shared resource with multiple threads in Java. Synchronization in Java guarantees that, no two threads can execute a synchronized method which requires same lock simultaneously or concurrently.

2. You can use java synchronized keyword only on synchronized method or synchronized block.

3. When ever a thread enters into java synchronized method or block it acquires a lock and whenever it leaves java synchronized method or block it releases the lock. Lock is released even if thread leaves synchronized method after completion or due to any Error or Exception.

4. Java Thread acquires an object level lock when it enters into an instance synchronized java method and acquires a class level lock when it enters into static synchronized java method.

5. Java synchronized keyword is re-entrant in nature it means if a java synchronized method calls another synchronized method which requires same lock then current thread which is holding lock can enter into that method without acquiring lock.

6. Java Synchronization will throw NullPointerException if object used in java synchronized block is null e.g. synchronized (myInstance) will throws java.lang.NullPointerException if myInstance is null.

7. One Major disadvantage of Java synchronized keyword is that it doesn't allow concurrent read, which can potentially limit scalability. By using concept of lock stripping and using different locks for reading and writing, you can overcome this limitation of synchronized in Java. You will be glad to know that java.util.concurrent.locks.ReentrantReadWriteLock provides ready made implementation of ReadWriteLock in Java.

8. One more limitation of java synchronized keyword is that it can only be used to control access of shared object within the same JVM. If you have more than one JVM and need to synchronized access to a shared file system or database, the Java synchronized keyword is not at all sufficient. You need to implement a kind of global lock for that.

9. Java synchronized keyword incurs performance cost. Synchronized method in Java is very slow and can degrade performance. So use synchronization in java when it absolutely requires and consider using java synchronized block for synchronizing critical section only.

10. Java synchronized block is better than java synchronized method in Java because by using synchronized block you can only lock critical section of code and avoid locking whole method which can possibly degrade performance.

11. Its possible that both static synchronized and non static synchronized method can run simultaneously or concurrently because they lock on different object.

12. From java 5 after change in Java memory model reads and writes are atomic for all variables declared using volatile keyword (including long and double variables) and simple atomic variable access is more efficient instead of accessing these variables via synchronized java code.

13. Java synchronized code could result in deadlock or starvation while accessing by multiple thread if synchronization is not implemented correctly.

14. According to the Java language specification you can not use Java synchronized keyword with constructor it’s illegal and result in compilation error. So you can not synchronized constructor in Java which seems logical because other threads cannot see the object being created until the thread creating it has finished it.

15. You cannot apply java synchronized keyword with variables and can not use java volatile keyword with method.

16. Java.util.concurrent.locks extends capability provided by java synchronized keyword for writing more sophisticated programs since they offer more capabilities e.g. Reentrancy and interruptible locks.

17. Java synchronized keyword also synchronizes memory. In fact java synchronized synchronizes the whole of thread memory with main memory.

18. Important method related to synchronization in Java are wait(), notify() and notifyAll() which is defined in Object class. They are defined in java.lang.object class instead of java.lang.Thread

19. Do not synchronize on non final field on synchronized block in Java. because reference of non final field may change any time and then different thread might synchronizing on different objects i.e. no synchronization at all. example of synchronizing on non final field :


private String lock = new String("lock");
synchronized(lock){
System.out.println("locking on :"  + lock);
}

20. Its not recommended to use String object as lock in java synchronized block because string is immutable object and literal string and interned string gets stored in String pool. so by any chance if any other part of code or any third party library used same String as there lock then they both will be locked on 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) {
      ........
   }
}