Tuesday, May 31, 2016

Java : Usage of SerialversionUID in Detail and How to generate serialversionUID manually

For the clear understanding of this concept you need to be aware of the Serialization and Deserialization concepts of Java.
What we have in Serialization as an overview is:

1)The class which needs to be traveled on network and to be saved anywhere ,must implement the java.io.Serializable interface.

2)All of the fields in that class must be Serializable. If a field is not Serializable, it must be marked transient so that compiler comes to know that this field need not to be saved.

3) The ObjectOutputStream class is responsible to serialize an Object.

4) A file named Engineer.ser is created after the serialization is completed (the class name is Engineer.java).

Following lines of code might be used as a summary:

 FileOutputStream fileOut = new FileOutputStream("/tmp/Engineer.ser");
         ObjectOutputStream out = new ObjectOutputStream(fileOut);
         out.writeObject(e);         // e is the instance of the class Engineer.java
         out.close();
         fileOut.close();

Hence , writeObject is responsible method to serialize the object.Here is magic of serialversionUID takes place. Keep going for the suspense.

On the other hand, when we Deserialize the object back and convert it to the object itself then the readObject method comes into ground.

The signatures of these two methods are as follows:

public final void writeObject(Object x) throws IOException

public final Object readObject() throws IOException, ClassNotFoundException


Now you might be clear about the usage of writeObject and readObject methods , lets proceed towards the concept of serialversionUID.

Every class which we are going to serialize must have a serialVersionUID . This is nothing but Universal Version Identifier. This is used when we Deserialize the class. It checks on the time of Deserialization that whether it is the same class or modified one. It matches up the serialversionUID which was created on the time of serialization. If it does not see the same serialVersionUID then it throws the InvalidClassException.


If you don't provide the serialversionUID to the class then it will create its own.

For example, if you serialize an object of Class Engineer version 1 (E1) which doesn't have a serialversionUID, then you modify it to version 2 (E2) and save it, you'll have two saved files, one with E1 and one with E2 objects. At this point no matter what serial version ID you put in the class, you will be unable to Deserialize one of the saved files.

Hence, if you will put the serialversionUID then there will not be any problem because Deserialization process will get the same serialversionUId all the times and would come to know that this is the same class which was serialized.


How to compute a serialVersionUID ?

There is a serialver tool available if we need to compute the serialVersionUID at any time. It is inbuilt with JDK.

In our case class is Engineer.java and suppose it is in the com.abc package then the computation of serialVersionUID would be like:

1) Open the console.
2) Put the following code and press enter.

serialver com.abc.Engineer

and you'll get output like this:

com.abc.Engineer:    static final long serialVersionUID = -8718469741124325816L;

You can take the code starting with "static" and place it inside your class with other static variables. Now the serial version ID is locked in your class.

Monday, May 30, 2016

Volatile Keyword In Java

We will cover the following about Volatile keyword in this section:

1) What is Volatile Keyword.
2) When to use it?
3) Some points to note about Volatile .
4) Why it is always compared with Synchronized ?
5) Comparison of Volatile and Synchronized :

Let's start the journey:

1) What is Volatile Keyword.
Although, it is rarely used keyword in java yet is the important concept to understand. We can understand this keyword in straight words by saying that the variables which are declared as volatile , the value of those variable will be stored into the main memory directly every time they are updated by the different threads. Hence, every thread will get an updated value of these variables. The volatile keyword can only be applied to a variable, it can not be applied to a class or a method. using volatile keyword along with class and method will result in a compiler error.

2) When to use it?
This variable should be used with the Multi-threading(for example). If we don't use volatile             keyword then the Thread X will not know that variable has been changed by Thread Y. Let's take    an example:

public class ABC extends Thread {
private volatile boolean takeAPause;

public void run() {
while (!takeAPause) {
//further code
}
}
public void commandForStop() {
takeAPause = true;
}
}

Here, If the variable is not declared as volatile, Then the current thread which is in loop will cache the value of the variable at the first round and will never read it again from the memory . By keeping this as volatile, it is guaranteed that the value will come directly from the memory in each round of the loop.

3) Some points to note about Volatile .
* The volatile in Java is only applicable to a variable and using volatile keyword with class and method is a compiler error.
* Volatile guarantees that value of the volatile variables will always be read from main memory directly and not from Thread's local cache.
* Reads and writes are atomic for all variables declared using volatile keyword.
* Changes to a volatile variable are always visible to other threads.
* An access to a volatile variable in never has a chance to block any functionality as this is

4) Why it is always compared with Synchronized?
It is always compared to the Synchronized because both the concepts are under the hood of multi-threading and are related to the variable access-ness throughout the multiple threads.

5) Comparison of Volatile and Synchronized :
Lock : Volatile takes the lock on the variable level globally while Synchronized takes the lock on the monitor level globally.
Null : Null is not allowed in Synchronized while null is allowed in Volatile.
Blocking : Blockage can occur due to Synchronized while blockage can not occur due to Volatile.
Performance : We should use volatile if we are really concerned about the performance other than Synchronized.

Friday, May 27, 2016

Java : Context Switching in Multithreading

When there are multiple threads running in the application, then the CPU cycles are pre-empted from one process and provided to another one based on the high priority or any other algorithm that is being used in that.
The pre-empting of CPU cycles from one process so that the CPU can be available to the second process is called as Context Switching.

Context Switching can be explained in a better way by an example of copy and paste that we use daily.

Let us copy a paragraph "Copied Paragraph" by using CTRL+C or copy command and delete this "Copied Paragraph" before pasting the copied content. The paragraph will be pasted wherever you want. That happens because when we copy the paragraph it is copied instantly and pasted in memory context on a common place which is accessible easily to each process. And when we use to paste it anywhere then the content is not coming from the copied address but is coming from that common place where CPU has pasted the content on the time of copy. Hence, a context is used in between the copy and paste processes. It seems that the pasted data is coming from directly the place from where we have copied that but in real the data is getting pasted in the context at the time of copy and is copied again from there and pasted to the location where we want it at the time of paste process. This is called the context switching.

Hence , in Multi-threading when the cycles of a thread are pre-empted then the state of the thread is saved to the context and is resumed from the context when the CPU comes back to this thread to execute its remaining part. So, its impossible to work with threads without context switching. Although its a basic discussion about this topic and one can dig into it much more. 

Thursday, May 26, 2016

this keyword in Java and How "this" holds the reference of the current object in Java

However, everybody who belongs to Java family knows that "this" holds the reference of current object. But, the original effort comes in ground when the question is asked from another corner and that is : How "this" holds the reference of current object. How come the reference of current object in "this" keyword.

Well, nothing to worry, here is the explanation.

Let's creat a class as follows:

public class ReferenceTest{
int a;
int b;

public ReferenceTest(int x,int y){
this.a=x;
this.b=y;
}

public static void main(String arg[]){

ReferenceTest rt = new ReferenceTest(10,20);
System.out.println("value of a is "+rt.a +" and the value of b is "+rt.b);

}
}

So, as we see the assignment of x in "this.a=x" goes to a which is a variable of this class.
It means this is containing the reference rt. But, how rt reaches to this keyword is the whole suspence.

Well, let's proceed a step ahead. If we dig into the details of the implementation and the java code written for constructors ,that is abstract from the end user, we will find the below story:

public class ReferenceTest{
int a;
int b;

public ReferenceTest(int x,int y,ReferenceTest this){
this.a=x;
this.b=y;
}

public static void main(String arg[]){

ReferenceTest rt = new ReferenceTest(10,20,rt);
System.out.println("value of a is "+rt.a +" and the value of b is "+rt.b);

}
}

It means when we are creating the object of this class and compiles it, compiler itself sends the reference of current object (rt in our case) to the constructor and "this" is just the variable name which is containing the current object reference in this way. Hence, whatever the operation we will perform on "this" , that would be reflected to the current object. That' it.

Kindly comment below if you have any question or query regarding this.

Happy Learning.

Tuesday, May 24, 2016

Difference between subsequence and substring in Java

Although we know that String.subSequence and String.subString methods produce the same output yet there are some differences in these methods . Also, we will go through the concept that why String has subSequence method at all when we have subString method.


1) Return Type :: String.subSequence(begin,end) method returns a CharSequence while String.subString(begin,end) returns the String reference. Although it does not make any difference to the end result and both will be same.
For Example:
String string = "Punia";
CharSequence subSequence = string .subSequence(0,2);
String subString = string .subString(0,2);

If we print the values of subSequence and subString, it will be Pu in both the cases. Hence the only difference is the return type. Below are the signatures of both:

public CharSequence subSequence(int beginIndex, int endIndex)
public String substring(int beginIndex, int endIndex)

2) Consecutivity : If we talk about the basics of these two concepts, Substrings are the consecutive combinations of the letters while subsequences are the non-consecutive combinations, like:

if "abc" is series of characters then ,

substrings: a, ab, abc, bc, c and the empty substring.
subsequences: a, b, ab, c, ac, bc, abc and the empty subsequence.


From the upper points , it is clear that there is no difference in usage of these two methods, So why the core team of java put the subsequence method in the methods list of Stirng class. Here is the reason.

String class implements the CharSequence interface. And, CharSequence interface have a method named subSequence, hence String must give the implementation of this method whether it's functionality is similar to the substring or not.

Although, it's a point of confusion that they could have avoided the substing(begin,end) method to be defined in the String class. The reason is, they could not stop the subsequence method to come in the class if they are implementing the CharSequence interface. Rather, they could stop themselves to put the substring(begin,end) mehtod in the String class. They could have defined other Substring methods with different parameters plus this subsequence method is dropping in from CharSequence interface. Might be a matter of thought.

Java : How To Calculate Manually The Hashcode Of Any String OR How hashcode method works internally to calculate hashcode of a String

Though its not such a practical thing that would be needed in daily practices of coding, yet we are going to cover this part of String because its been asked by many interviewers now a days and can also be used in some situations while coding where it requires to calculate the hashcode and the developer needs some further operations on the calculated hashcode.

Well, we have a simple formula for calculating the hashcode of any String manually and that is :

hashcode = s[0]*31^(n-1) + s[1]*31^(n-2) + ......................+s[n-1].

Here, s[0], s[0] ...s[n-1] are the ASCII values of the characters occurring in the String. n is the length of the String.

For example:

            Let us suppose, we have a String like follows.
            String str = "ab";

and we run str.hashcode() then it will produce the output as 3105. Here is how it comes,

hashcode = ASCII(a)*31^(1) + ASCII(b);
               = 97*31+98=3105.

And this is the reason why the hashcode of space(" ") is equal to the ASCII value of space (" ").

Also, the same reason why the hashcode of empty string is ZERO.

That's it. Kindly, post in the comments if you have any questions or queries regarding this. Happy learning.