Thread leak with ImageLoadWorker in Flying Saucer jar

Problem :

If you have used Flying Saucer \ HTMLRenderer jar in your code for “HTML to PDF” conversion then you have faced Thread leak in ImageLoadWorker and eventually it make your system down. Further if you will monitor your system in Java melody or Jmeter you will find out that each request for “HTML to PDF” conversion is leaving 5 threads open.

Solution :

To solve this problem you just need to put a properties file( Eg : htmlrenderer.properties) some where in your system which is reachable from your application. Put below entries in properties file.

xr.image.background.loading.enable=false
xr.image.background.workers=0

In your code at start of the application set the path of this file in system properties like given below.

//Absolute path of that file
System.setProperties("xr.conf","D:\\htmlrendererconf\\htmlrenderer.properties");

As you have set workers count zero in properties file, it will generate zero unused threads and your problem is solved.

Other related posts are :
HTML to PDF conversion in JAVA | HTML to PDF example in JAVA
ThreadPoolExecutor and BlockingQueue with an example
Concept of AOP (Aspect oriented programming) every spring programmer use without knowing about it .
Top 10 spring interview questions and their answers. Spring basic concepts.

Please share this posts on Facebook,Linkeedin,Google+,Twitter by clicking on below icons.

Advertisements

ThreadPoolExecutor and BlockingQueue with an example

After Java 5 ThreadPoolExecutor changed the way of multi threading in Java . It was a nightmare to implement multi threading prior to Java 5 but with the help of ThreadPoolExecutor the situation has changed . I am going to explain how to use it and meaning of different fields of it .

Step 1 :Create a thread class .

package com.technotailor;
 
public class DemoThread implements Runnable 
{
    private String name = null;
 
    public DemoThread(String name) {
        this.name = name;
    }
 
    public String getName() {
        return this.name;
    }
 
    @Override
    public void run() {
        try {
            System.out.println("Before sleep : " + name);
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("After sleep : " + name);
    }
}

Step 2 : Let’s understand blocking queue now . If you remember any multi threading interview before Java 5 then Producer-consumer problem was the favorite question of any interviewer . By use of blocking queue you do not need to write any code for this, ThreadPoolExecutor put every thread in this queue as a worker until it got processor to run this thread . You can create object of blocking queue by giving it a size . Do not afraid by it’s name it is not blocking anything , It’s just keeping objects until processor is available to execution .

BlockingQueue<Runnable> blockingQueue = new ArrayBlockingQueue<Runnable>(50);

Step 3 : To create a thread pool executor object, you need to provide few values .

ThreadPoolExecutor executor = new ThreadPoolExecutor(5,20, 5000, TimeUnit.MILLISECONDS, blockingQueue);

Let’s understand them in sequence of their value in object creation .
Core pool size : First one is core pool size which we gave value as 5 above . Core pool size is the value that how many parallel threads will be running at one point of time .

Max pool size : Second one is max pool size . Max pool size is not useful in every case .There are two scenarios given below .
In first scenario, if in your functional requirement someone going to hit you with opening threads without looking for your capacity , then max pool size will help you . If someone is giving you thread on speed more then threads execution time and your blocking queue is full with having 50 threads in it then up to max pool size ThreadPoolExecutor will handle the request before rejecting it by throwing exception .
In second scenario if your functional requirement says that someone will only provide you objects or threads according to your capacity then remainingcapacity() method of blocking queue can help and max pool size will not be required .

if(blockingQueue.remainingCapacity()>0){}

Idle time and it’s unit : This is a time for which a thread will wait for a new worker(When we fire executorr.execute() method on one object it adds in blocking queue and become worker before it gets processor or any empty thread to run on ) to come before it will return to it’s pool .

Blocking queue object : We already know enough about it, still this is a queue where all worker waits for their task .

Step 4 : Lets run above thread class with these settings .

package com.technotailor;
 
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
 
public class DemoExecutor 
{
    public static void main(String[] args) 
    {
        Integer threadCounter = 0;
        BlockingQueue<Runnable> blockingQueue = new ArrayBlockingQueue<Runnable>(50);
 
        ThreadPoolExecutor executor = new ThreadPoolExecutor(10,
                                            20, 5000, TimeUnit.MILLISECONDS, blockingQueue);
 
        executor.setRejectedExecutionHandler(new RejectedExecutionHandler() {
            @Override
            public void rejectedExecution(Runnable r,
                    ThreadPoolExecutor executor) {
                System.out.println("DemoTask Rejected : "+ ((DemoThread) r).getName());
            }
        });
        while (true) {
            threadCounter++;
            if(executor.getQueue().remainingCapacity()===0){
            	break;
            }
            // Adding threads one by one
            System.out.println("Adding DemoTask : " + threadCounter);
            executor.execute(new DemoThread(threadCounter.toString()));
        }
    }
 
}

As you can see how easy it is to handle threads now . You just need to provide configuration rest is in hands of ThreadPoolEecutor .

For more information, see the Thread Pool Exeutor

Other related posts are :
Concept of AOP (Aspect oriented programming) every spring programmer use without knowing about it .
Set datasource spring bean properties dynamically if server is not available
Top 10 spring interview questions and their answers. Spring basic concepts.
HTML to PDF conversion in JAVA | HTML to PDF example in JAVA

Please share this posts on Facebook,Linkeedin,Google+,Twitter by clicking on below icons.

Concept of AOP (Aspect oriented programming) every spring programmer use without knowing about it .

Many of spring programmer these days, when it’s comes to AOP (Aspect oriented programming) says heard about it but never used it . It’s interesting to see that many of them use it without knowing about it . One of the example that most of us used is spring declarative transaction management annotation. We do know what @transactional annotation does but we do not know and doesn’t even care about how it is doing it ? Spring is using AOP here .

Let’s understand how AOP actually works . Well in theory when one bean(java object) call method of another bean then spring create a proxy between them . If there is an interface for that bean and coding is on that interface than it will work as proxy otherwise spring will create a proxy for it . This proxy can be programmed through AOP and we can code if we want to do something before method call,after method call,after exception throw etc .

Now let’s see how this theory works in actual . Let’s create one custom annotation like @transactional to understand it better .

Step 1 : To work AOP with spring we need to define

<aop:aspectj-autoproxy>

in custom-config.xml .

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"        xmlns:context="http://www.springframework.org/schema/context"        xmlns:aop="http://www.springframework.org/schema/aop"        xmlns:mvc="http://www.springframework.org/schema/mvc"        xsi:schemaLocation="            http://www.springframework.org/schema/beans            http://www.springframework.org/schema/beans/spring-beans-3.2.xsd            http://www.springframework.org/schema/context            http://www.springframework.org/schema/context/spring-context-3.1.xsd            http://www.springframework.org/schema/aop         http://www.springframework.org/schema/aop/spring-aop-3.0.xsd        http://www.springframework.org/schema/mvc        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

  <!-- Scans for application @Components to deploy -->
    <context:annotation-config/>
  <context:component-scan base-package="com.stevenlanders.*" />

  <!-- enable AOP -->
  <aop:aspectj-autoproxy/>

</beans>

Step 2 : Create you custom annotation .

@Retention(RetentionPolicy.RUNTIME)
public @interface LogDuration {
   String value();
}

Step 3 : Write your AOP class. To do it, You need to use @Aspect annotation on that class . Then you need to create advice in this class. To do so, You need to choose one of the annotation given below .
@Before – Run before the method execution
@After – Run after the method returned a result
@AfterReturning – Run after the method returned a result, intercept the returned result as well.
@AfterThrowing – Run after the method throws an exception
@Around – Run around the method execution, combine all three advices above.
We are going to choose @Around here as we need to start and stop timer before and after of this method execution .

@Aspect
public class AopExample{

    //for any method with @LogDuration, no matter what the return type, name, or arguments are, call this method
    @Around("execution(@com.stevenlanders.annotation.LogDuration * *(..)) && @annotation(logDurationAnnotation)")
    public Object logDuration(ProceedingJoinPoint joinPoint, LogDuration logDurationAnnotation) throws Throwable {

        //capture the start time
        long startTime = System.currentTimeMillis();

        //execute the method and get the result
        Object result = joinPoint.proceed();

        //capture the end time
        long endTime = System.currentTimeMillis();

        //calculate the duration and print results
        long duration = endTime - startTime;
        System.out.println(logDurationAnnotation.value()+": "+duration+"ms"); //you should use a logger  

        //return the result to the caller
        return result;
    }

}

Step 4 : Put your annotation on methods for which you want to print execution time .

@Controller
public class ExampleController{

     @RequestMapping("/api/example/hello")
     @LogDuration("Hello World API")
     public @ResponseBody String getHelloWorld(){
          try {
            Thread.sleep(3000);
          } catch (InterruptedException e) {
            throw new RuntimeException("Sleep Interrupted", e);
          }
          return "Hello World";
     } 

}

Step 5 : Run this code .

Hello World API: 3002ms

For more information, see the Spring AOP Documentation

Other related posts are :
Interview questions on concept of code on interface rather then class
JPA Hibernate Sequence generator generating odd ID value and IntegrityConstraintVolation exception is coming
Top 10 spring interview questions and their answers. Spring basic concepts.
Logback logs are not working. Log4j logs are not working. Steps to make logging work.

Please share this posts on Facebook,Linkeedin,Google+,Twitter by clicking on below icons.

Interview questions on concept of code on interface rather then class

Oops concept is always a must to have skill by an interviewee. Today i am going to explain interview question-answer and practical implementation of one oops concept which says Code on Interface rather then a Class.

Question1 : What does code on interface rather then class means.
Answer : This is an oops concept which says that we should call methods of a class with the reference of it’s interface rather then that class itself.

Question2 : Then interviewer asked what is the benefit of using interface reference .
Answer : I explained it with the help of example. If we have a restro-bar entity Which have both food items and drink items as its methods . When we go in restro bar and we want to drink then they will provide us two seperate menu for drink and eat(two interfaces), so that we can choose easily between drinks items(drink interface) and inspite of restrobar(class) have eat items too but it won’t bother me . So having two seperate interfaces made customer choose easily between items according to their concerns .


public interface DrinkMenu {
public List drinkItems();
}
public interface FoodMenu {
public List foodItems();
}

public class RestroBar{
public List drinkItems(){
List drinkItems=new ArrayList();
//add drink items
return drinkItems;
}
public List foodItems(){
List foodItems=new ArrayList();
//add food items
return foodItems;
}
}

Question 3 : Then interviewer asked me what if i want to order food from different restaurants daily but does not want to give different websites to order, how could i achieve this.
Answer : Now definitely he wants to understand if i can use interface practically and solve his problem. So i told him to solve this problem we need an interface having method which will return list of food items and different restaurants(Classes) will implement this method and will return filled list with their food items.

public interface Restaurants {
public List foodItems();
}
public class ChawlaRestaurant{
public List foodItems(){
List foodItems=new ArrayList();
//Chawla food items
return foodItems;
}
}
public class HaweliRestaurant{
public List foodItems(){
List foodItems=new ArrayList();
//Haweli food items
return foodItems;
}
}

Now we need a factory which will return Restaurants interface reference holding particular restaurant object by taking restaurant name as input.


public class ObjectFactory{
public Restaurants getRestaurantObject(String restaurantName){
Restaurants restaurants = //By using reflection we can create obect
return restaurants;
}
}

Now in main class which will be access by user we will get hotel name input from user then that restaurants object from factory at run time and then food items of that particular restaurant.


public class UserInput{
public class displayFoodItems(String restaurantName){
ObjectFactory objectFactory=new ObjectFactory();
Restaurants restaurants = objectFactory.getRestaurantObject(restaurantName);
List foodItems = restaurants.foodItems();
for(String foodItem : foodItems){
system.out.println(foodItem);
}
}
}

Please Ask Questions or give suggestions through comments in below section .

Other related posts are :
JPA Hibernate Sequence generator generating odd ID value and IntegrityConstraintVolation exception is coming
Top 10 spring interview questions and their answers. Spring basic concepts.
Logback logs are not working. Log4j logs are not working. Steps to make logging work.
MQ connection not closed and giving MQ Error-2009

Please share this posts on facebook,Linkeedin,Google+,Twitter by clicking on below icons.

Interview question on same name entity twice in Jpa/Hibernate

Recently when one of my friend went for an interview then interviewer trap him into an interesting question and he discussed with me, so i thought to share his experience .

Question 1 : Interviewer asked him if we can have two entity for a single table .
Answer : He said yes we can have two entity for same table name if we want to, JPA/Hibernate does not stop us from doing that .

Question 2 : Then interviewer asked him, What is DuplicateMappingException : duplicate import.
Answer : Now my friend got stuck because he does not know answer of this question . So he came too me after interview and discuss it with me . Then i told my friend that this exception occurs when we have two same name java class having @entity annotation in different package. Actually what JPA does that it gave a unique name to each entity you define with @entity annotation as defined below .


package com.google.employee;
@Entity
@Table(name="GOOGLE_EMPLOYEE")
public class Employee{
}

package com.ask.employee;
@Entity
@Table(name="ASK_EMPLOYEE")
public class Employee{
}

As we did not provide any name inside @Entity annotation so, JPA gave class name as entity name. JPA does not allow two same name entity and will give exception Entity name must be unique in a persistence unit . So if we want to have two same name classes in different package as our entity then we should provide a name as given below.


package com.google.employee;
@Entity("GoogleEmployee")
@Table(name="GOOGLE_EMPLOYEE")
public class Employee{
}

package com.ask.employee;
@Entity("AskEmployee")
@Table(name="ASK_EMPLOYEE")
public class Employee{
}

and we will use this name in named queries after from clause too.

select askEmployee from AskEmployee askEmployee where askEmployee.employeeName=:emplyeeName

Please Ask Questions or give suggestions through comments in below section .

Other related posts are :
JPA Hibernate Sequence generator generating odd ID value and IntegrityConstraintVolation exception is coming
Top 10 spring interview questions and their answers. Spring basic concepts.
Logback logs are not working. Log4j logs are not working. Steps to make logging work.
MQ connection not closed and giving MQ Error-2009

Please share this posts on facebook,Linkeedin,Google+,Twitter by clicking on below icons.

Are Payment banks a competitive threat or addon to the traditional banking.

Few Days before i read a news that RBI governor “Mr. Raghuram Rajan” announced 13 new banks, Infact 2 banks and 11 payment banks.
Raghuram Rajan
First thing came in my mind was that how these so called traditional banks let that happen , I mean who like the competition at such a vast level . Then i thought what if these payment banks are not competition to them, infact this is what existing banks wants to happen from a long time. Now you ask why ???

Actually retail customer and their small transactions are overhead to these traditional banks they only like Corporate user,Loan user(retail and corporate both),Credit card users etc. but they have to entertain retail user because of RBI norms. Now days when retail customer is purchasing approximately everything online and making many transaction in one day, this overhead is increasing more and more to these banks . On the other hand these payment banks will be very happy to entertain these customers because their business model will depend on selling things online, collaboration with merchant sites(Amazon, Flipkart, Snapdeal etc), online advertisements etc, So they will not have any conflict or competition with each other.
In payment banks you can have money upto 1 lakh,they will provide interest on that money like saving account. So now question arise if a retail customer like you and me have both options, why i will go for payment bank instead of existing bank. So to attract customers these banks will start providing cashbacks on online purchases , which existing banks don’t do .

Payments banks add-ons, not competitors: Raghuram Rajan

Other related posts are :
How to render HTML in java
Top 10 spring interview questions and their answers. Spring basic concepts.
Logback logs are not working. Log4j logs are not working. Steps to make logging work.
Set datasource spring bean properties dynamically if server is not available

Please share this posts on facebook,Linkeedin,Google+,Twitter by clicking on below icons.

HTML to PDF conversion in JAVA | HTML to PDF example in JAVA

HTML to PDF conversion is the most searched topics on google by Java developers. So I am going to explain steps to do it with example of code.

Step 1 : In step one we will render html object like browser render it, so that DOM(Document Object Model) can be clean and fire events like “document ready” and “body onload”. We can do it with help of htmlunit and htmlcleaner jars . To learn how to do it please click on below link.

How to render HTML in java

Step 2 : If you do not want to render html string and only wants to convert it to PDF as is, then you can avoid step 1 and convert that HTML string into DOM with help of DocumentBuilder.


DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(""));
Document document = db.parse(is);

Step 3 :In step three we will convert that rendered/parsed object into PDF with help of Itext and CoreRenderer Jars. Below is the code given for it.

ITextRenderer renderer = new ITextRenderer();
renderer.setDocument(document,"file:///"+templateLogoPath);
File pdfFile = new File(filePath+pdfFileName);
OutputStream outputStream = new FileOutputStream(pdfFile);
renderer.layout();
rootLogger.debug("Before create PDF with file name --> "+pdfFileName);
renderer.createPDF(outputStream,true);
rootLogger.debug("After create PDF with file Name -->"+pdfFileName);
renderer.finishPDF();
outputStream.flush();
outputStream.close();

This is it now you have converted PDF object.
Jars required for this are :

  1. Itext
  2. CoreRenderer

Please Ask Questions or give suggestions through comments in below section .

Other related posts are :
How to render HTML in java
Top 10 spring interview questions and their answers. Spring basic concepts.
MQ connection not closed and giving MQ Error-2009
Logback logs are not working. Log4j logs are not working. Steps to make logging work.

Please share this posts on facebook,Linkeedin,Google+,Twitter by clicking on below icons.

How to render HTML in java

When we open a html content in browser then browser render that html also fire events like “document.ready”,”body onload”. Java script code do whatever we write in that code for document ready function. Eg: Render some grid on Document ready,show some image on basis of some condition etc.
But when we have that html code as a string in java and we want the html rendered object(with document ready and body onload functionality) in java then we need renderer API .
We majorly get this type of requirement when we need to create PDF from html or we want to write html object as input stream on some protocol etc.
Htmlunit and HTML Cleaner is the widely used API in java for this functionality.

I am going to explain below how to use it in java .

public void renderHtml(String htmlToConvert){
HtmlCleaner cleaner = new HtmlCleaner();
ByteArrayOutputStream out = new ByteArrayOutputStream();
final WebClient webClient = new WebClient();
try
{
String htmlFileName="D:\\gaurav\htmlFile.html";
String pdfFileName=null;
File htmlFile = new File(filePath+htmlFileName);
FileWriter fileWriter = new FileWriter(htmlFile);
BufferedWriter writer = new BufferedWriter(fileWriter);
writer.write(htmlToConvert);
writer.close();
fileWriter.close();
final HtmlPage page = webClient.getPage(htmlFile.toURI().toURL().toString());
final String pageAsXml = page.asXml();
system.out.println("Before tag node -->"+pageAsXml);
TagNode node = cleaner.clean(pageAsXml);
DomSerializer domSerializer = new DomSerializer(props);
Document document = domSerializer.createDOM(node);
new PrettyXmlSerializer(props).writeToStream(node, out);
out.flush();
out.close();
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
webClient.closeAllWindows();
if(webClient!=null && webClient.getCookieManager()!=null)
{
webClient.getCookieManager().clearCookies();
}
}
}

HtmlCleaner cleans the html. Eg: If there is a tag which is not closed then it make them close to make html proper.
Htmlunit then perform rendering.
Jars required for these functionality are given below:

  1. htmlcleaner-2.2.jar
  2. htmlunit-2.14.jar
  3. htmlunit-core-js-2.14.jar
  4. httpclient-4.3.2.jar
  5. httpcore-4.3.1.jar
  6. httpmime-4.3.2.jar

You can download these jars from sourceforge or mvnrepository .

If you want to learn how to convert this rendered HTML object into PDF please click on below link

HTML to PDF conversion in JAVA | HTML to PDF example in JAVA

Please Ask Questions or give suggestions through comments in below section .

Other related posts are :
HTML to PDF conversion in JAVA | HTML to PDF example in JAVA
Top 10 spring interview questions and their answers. Spring basic concepts.
MQ connection not closed and giving MQ Error-2009
JPA Hibernate Sequence generator generating odd ID value and IntegrityConstraintVolation exception is coming

Please share this posts on facebook,Linkeedin,Google+,Twitter by clicking on below icons.

String interview questions and answers

String is favourite topic of any java programmer and interviewer. Every interviewer think that at least interviewee should have knowledge about string if he is saying that he is a java developer.

Top String interview questions

Question 1 : What is String in java. Is string a data type.
Answer : It will be first question to start so your answer will be. String is not a primitive data type in java like long and int. String is a class in java which contain it’s content as character array. It resides in java.lang package. It provide different methods like equal,concat,substring etc. to provide character operations .

Question 2 : How to define String in java. What is string pool .
Answer : There are two ways to define string in java.

String s1 = new String("string1");
String s2 = "string2";

In first one we have created a new object of string class by having content as “string1”. We can also define string by only using double quotes as defined in second line. If he have not asked about string pool still it’s time that you mention stringpool to make your interview excited by telling difference between both methods. Difference between both in java is that in first one object is created in heap but in second way object will be created in string pool if only there is not a object having same content “string2” in pool. If there is an object having content “string2” in pool then JVM will point String s2 to the same object . Like in below code string3 and string2 of above code will point to same object in pool .
String s3 ="string2";
Note, benefit of string pool is that JVM is not creating so many objects for single content .

Question 3 : If two references are pointing to same object then what will happen when we perform operation on one referenced object.
Answer : Well now he wants to know if you know about immutability of string class. You will answer that as string is immutable(String class is final) in java so you can not change already created object. So if two reference will point to same object it will be same for both reference like s2 and s3 having above.
When you perform operation on s2 it will create a new object. If you want s2 to hold changed data then you have to assign s2 that new object.
s2 = s2.subString(0,1);
Now s2 have a separate object with content “s” and s3 still having object with content “string2”.

Question 4 : How can i put a string object created with new keyword in string pool.
Answer : To achieve that you have to execute intern() method on that object because by default that object will be in heap memory not in pool. This question will be asked by interviewer if he have knowledge about intern method.

Question 5 : How to compare two Strings in java program.
Answer : String class overrides equals method of object class to provide it’s own functionality and that equal method compare content of two string object and return true and false accordingly. Also there is equalsIgnoreCase method which compare string without caring about their upper case or lower case .It uses String CASE_INSENSITIVE_ORDER Comparator for case insensitive comparison.

Question 6 : How does substring works.
Answer : Most people have used this method in his life but many of us does not have idea how doest it work internally. In substring method string class convert first string to char array. Then it define one more char array of same length. Then it took characters from first char array to another char array on basis of given index in sustring method. Well if an interviewer is smart then he may ask if original string and substring are using same length char array then it may create memory leakage then answer is yes unintentionally but yes. Only when a very big string is converting into a very small string by substring method.

Question 7 : Can we use string inside switch case.
Answer : After java7 we can use string in switch case. But upto java6 we can not use string in switch case we have make if-elseif chain to acheive this.

Question 8 : Is string threadsafe.
Answer : Due to immutabilty string is thread-safe in java because thread can not change it and it’s value will be same for every thread.

Question 9 : What is difference between String,StringBuffer,StringBuilder.
Answer : Basic difference between all three is that string is immutable class but stringbuffer and stringbuilder are not.
Between stringbuffer and stringbuilder dufference is that buffer is thread safe so it’s slow performancewise respected to builder which is not thread safe.To know detailed discussion about them go to String vs StringBuffer vs StringBuilder.

Question 10 : What are other benefits of immutable functionality of string .
Answer : Due to being immutable is popular key inside Hashmap because it can not be changed it’s hashcode is cached at time of creation so it make best choice inside hashmap key because hashmap works searching on basis of hashcode.
Also we can use string to store password due to immutabilty hacker can not change it.

Other related posts are :
String vs StringBuffer vs StringBuilder
Top 10 spring interview questions and their answers. Spring basic concepts.
JPA Hibernate Sequence generator generating odd ID value and IntegrityConstraintVolation exception is coming
Set datasource spring bean properties dynamically if server is not available

Please share these posts on facebook,Linkeedin,Google+,Twitter by clicking on below icons.

String vs StringBuffer vs StringBuilder

Difference between String, StringBuffer and StringBuilder are popular interview questions in java.

Question 1 : What is difference between string and stringbuffer or stringbuilder.
Answer : String is an immutable class in java so you can not change it’s object once it is created. If you want to perform operation on this object then it will create new object. But when you want to perform operations on string value without creating multiple objects then java has provided two classes for this functionality. These classes are StringBuffer and StringBuilder. Both of these classes have all functionality provided by string without being immutable. So when should we use these two classes depends on our requirement.

For eg: If we require string value after performing multiple operations basis on some conditions then we should go for these classes.

Question 2 : What is the difference between StringBuffer and StringBuilder.
Answer : Next question of interviewer will be, If java have provided two classes then what is the difference between them or why there is two classes. Difference between these two classes is. StringBuffer is thread-safe so basically this class have synchronised methods so only one thread will access these method at a time and can change string value, so next thread will get updated value. When you are going to perform operation on string value in multi-threading environment then we should always use StringBuffer. On the other hand StringBuilder have same functionality as StringBuffer but it is not thread-safe. Then why should we use stringbuilder. Well when we want to perform operation on stringvalue in single threaded environment then we should use StringBuilder because it is much faster then stringbuffer. When we need performance in single thread environment then StringBuilder is right choice.

Other related posts are :
Top 10 spring interview questions and their answers. Spring basic concepts.
JPA Hibernate Sequence generator generating odd ID value and IntegrityConstraintVolation exception is coming
Set datasource spring bean properties dynamically if server is not available

Please share these posts on facebook,Linkeedin,Google+,Twitter by clicking on below icons.