Thursday, 14 September 2017

You don't create multiple instances of servlet. The servlet engine creates a separate Thread for each request (up to some max number of Thread) The performance is related to the number of Threads, not the number of instances of the servlet.

Each request is processed in a separated thread. This doesn't mean tomcat creates a thread per request. There a is pool of threads to process requests. Also there is a single instance for each servlet and this is the default case.(Some more information). Your servlet should be Thread Safe.

Wednesday, 2 August 2017

Mutable and Immutable In JAVA


Mutable Objects:


> Mutable Objects are those objects , whose fields and state can be changed after creation.

example:
 - StringBuilder Object


class Mutable
{
public static void main (String[] args) throws java.lang.Exception
{
StringBuilder sb=new StringBuilder("Hello ");  
                sb.append("World");//now original string object got changed  
                System.out.println(sb);//prints Hello World
}
}



explanation:






1> So we define StringBuilder object in the first Line . Now Point to be noted here is that sb is reference to the object "Hello".
   we always create reference to the object . So sb is reference to the object "Hello".
2> In the next line we are appending "World" in "Hello" String, Hence Content of the object gets changed and new content became "Hello World".







Immutable Objects:


>Immutable objects are those Objects, whose fields and state cannot be changed after its creation.

example:
- String Object

 class Immutable
{
public static void main (String[] args) throws java.lang.Exception
{
String str=new String("Hello ");  
                str.replace("o","w");//now original string is changed  
                System.out.println(str);//Still prints Hello 
}
}




Explanation:





1> Here we have created Reference str to the String object "Hello".
2> In the next line we are replacing "o" from the content  to "w".
3> Here the interesting point is Next Line where we are trying to print value of the str(reference to the object "Hello").
str still points to the same object "Hello" and its content doesnt get changed to "Hellw".
Hence Strings are Immutable in Java.
4> Basically here we are creating To string object one is "Hello" and another is "Hellw" in string Pool.
str refers to "Hello", and "Hellw" is without any reference in string Pool.



Bonus Tip:


what would happen when we do str=str.replace("o","w");?

1> would str will still point to string object "Hello"
2> or will it point to "Hellw"?

Answer:





As reference of str has changed when we do str=str.replace("o","w")
str will now point to new string object "Hellw", and "Hello" object will be without any reference in the string Pool.