October 24, 2016

Lyrics of Cutiepie from Ae Dil Hai Mushkil

Tere vargi na pind vich dooji, punjabi koi chick mahiya..
Kyun tu khidki te baithi sharmaaye, barande utte dikh mahiya..

October 19, 2016

#BiggBoss10 : Day 3 Synopsis

There seems to be no end to day 2 for the contestants inside the Bigg Boss house! The Maliks seems to be going great in the game and giving sleepless nights to the Sevaks. In the wee hours of the night, the commoners do a secret meeting in the washroom area and decide to trouble the celebrities. After much planning and plotting, Priyanka instructs Swamiji to ring the ‘Hukm Ki Ghanti’ after the Sevaks are fast asleep and demand for food. Swamiji relents to Priyanks’s idea. 

October 18, 2016

My love for fashion happened because of movies : Sonam Kapoor

Ever since Sonam Kapoor has been a part of the industry, she’s been hailed as THE Fashion Queen of the industry! So while her love for fashion is quite obvious, the reason behind that love is not!

#BiggBoss10 Synopsis Day 2 : The 1st task of the season ‘Raaz’ brings insecurities..

On day two, the contestants wake up dancing to the tunes of the song ‘Gupt Gupt’ unaware of what is in store for them. The day starts with fight over tasteless food as Manoj questions the culinary skills of the celebrities.

He comes whining to Karan and tells him that the food is ‘Vaahiyat’ and he would like to assist them in the kitchen going forward. Lopamudra jumps in the conversation and they soon have an argument.

Priyanka Jagga, being at her cunning best, continues to reprimand the sevaks and forces them to follow her orders. Bani asks her to show some ‘courtesy’ and use the word ‘Please’ while ordering around. Priyanka, however, takes offense to this.

Commoner Navin manages to irk Swamiji with his actions after which Swamiji claims that his health is deteriorating because of Navin’s torture. On the other hand, Gaurav and Akansha are seen bonding as he helps her with a manicure. Later in the day, Bigg Boss introduces the task ‘Raaz’ wherein the celebrities have to solve a riddle and find out that one big secret of the commoners. If they successfully decode all the secrets, they will become the maliks of the house while the Indiawale will become their sevaks. As soon as the task is introduced, fights and insecurities come to the fore while the gang of celebrities continue to strategize.

Swamiji, surprisingly, finds it difficult to deal with the precarious scenario and as a result, emerges as a troublemaker inside the house. From threatening Lopamudra to questioning Akansha’s intention towards Gaurav, he starts hurling harsh comments at every contestant. Later in the night, right before when the celebrities decide to retire for the night, Swamiji wakes them up and asks them to make food for him. Shocked by his behavior, Monalisa gets into an argument with him. Exhausted and tired, the celebrities’ first crib about following his orders but ultimately decide to give in.

Will celebrities finally get a chance to be the maliks, will they successfully beat Indiawale in the first task of the season?

Karan Sharma to tie the knot on 16th November..

TV actor Karan Sharma secretly got engaged to singer-turned-actress Tiaara Kar in February last year. The duo are all set to take their relationship to the next level by tying the knot on 16th November.

#BiggBoss10 Karan Mehra’s wife Nisha Rawal clears the air about their son..

There have been many speculations doing the rounds about Karan Mehra and Nisha Rawal having a one-year-old son. And the question again cropped up after Karan recently entered the reality show Bigg Boss. Putting all speculations to rest, Nisha Rawal has stated that they do not have a son.

In Beyhadh you will see two completely different shades of love: Imran Khan

Imran Khan, who was last seen in 'Mere Rang Mein Rangne Wali' made a comeback on small screen after almost one and a half year with Cinevistaas recently launched show 'Beyhadh' on Sony Entertaintment. He is playing a protective and loving father of Saanjh (Aneri Vajani) in the show.

October 17, 2016

#BiggBoss10 Synopsis Day 1: Celebrities become Sevak to commoners

The most awaited moment of Bigg Boss 10 is here! 15 dhamakedaar contestants have entered the Bigg Boss house and this crazy mix of celebrities and commoners is already creating storm inside. The day started with the contestants waking up to the song ‘Saare Niyam Tod Do’ but are soon introduced to the new rule book that they have to follow for the entire week. According to the rule book, the celebrities asked to be sevaks to the commoners and oblige all their requests.

October 12, 2016

Namish Taneja went for river rafting along with his co-star..

 Namish Taneja, who is currently seen as one of the protagonists in Colors' popular show 'Swaragini' recently got a day off after a hectic shooting schedule. The dashing actor made an impromptu plan and went for river rafting along with his co-star Tarun Singh and Sadda Haq fame Aashutosh Semwal.

#BiggBoss10: Introducing the 13 dhamakedaar shortlisted contestants of Bigg Boss Dus..

COLORS’ marquee reality show Bigg Boss has had the entire nation waiting in anticipation ever since the announcement that its gates have been opened to the aam aadmi to participate as contestants. As the show launches this weekend to create history, for the first time, a combination of celebrity contestants and the common man will live in the spotlight.

After months of auditions and scrutiny, for the first time ever, Bigg Boss announces the names of some of the shortlisted common man contestants who will engage in a battle of wits and entertainment with celebrities.

October 07, 2016

Rohitash Gaud bereaved..

Bhabi Ji Ghar Par Hai fame Rohitash Gaud’s dad passed away on Thursday. The actor received a call while he was shooting today for his show. He rushed to his hometown as soon as the news reached him.

October 05, 2016

This is how a traditional 'Gara' got a modern twist..

For many years, Perveez Aggarwal has showcased traditional Gara embroidery in her “My Beautiful Embroideries” collection. Parsi Gara embroidery is a status symbol and most women want to have at least one item from “My Beautiful Embroideries” in their wardrobes. These consist of saris, kurtis, shawls and stoles as well as jackets, beautifully combining the traditional and the modern. 

October 04, 2016

I am facing a dual challenge in Naagin 2 : Mouni Roy

When Naagin first premiered on COLORS last year, it shook the foundations of conventional viewership to carve a path as the No.1 blockbuster on Indian television.

Shivanya’s (Mouni Roy), an ichhadhari naagin, life took precedence as she sought revenge while guarding the nagmani from evil beings with her love, Ritik (Arjun Bijlani) by her side. And now it’s, Shivanya’s daughter, Shivangi’s turn to take the legacy forward as COLORS’ record-breaking finite fiction series returns for a brand new expedition with Naagin 2.

JSP Servlet Interview Questions and Answers

What is called servlet container?
A servlet container is a part of Web server that provides network services depends on request and response are sent, MIME based requests and responses. It contains and manages servlets through their life cycle.

What is the difference between Server and Container?
A server can provide service to the client and it contains one or more containers such as EJBs, Servlet, JSP containers. Containers hold set of objects.

Why HttpServlet class is declared abstract?
HttpServlet class provide HTTP protocol implementation of servlet but it’s left abstract because there is no implementation logic in service methods such as doGet() and doPost() and we should override at least one of the service methods. That’s why there is no point in having an instance of HttpServlet and is declared abstract class.

What are the functions of Servlet container?
1. Lifecycle management : Managing the lifecycle events of a servlet like class loading, instantiation, initialization, service, and making servlet instances eligible for garbage collection.
2. Communication support : Handling the communication between servlet and Web server.
3. Multithreading support : Automatically creating a new thread for every servlet request and finishing it when the Servlet service() method is over.
4. Declarative security : Managing the security inside the XML deployment descriptor file.
5. JSP support : Converting JSPs to servlets and maintaining them.

What is the difference between JSP and Servlets?
  • JSP is a webpage scripting language that can generate dynamic content. Where as Servlets are Java programs that are already compiled which also creates dynamic web content.
  • JSP run slower compared to Servlet as it takes compilation time to convert into Java Servlets.
  • It’s easier to code in JSP than in Java Servlets.
  • In MVC, jsp act as a view, where as servlet act as a controller.
  • The advantage of JSP programming over servlets is that we can build custom tags which can directly call Java beans.
  • JSP supports HTTP protocol which mainly used for presentation. But a servlet can support any protocol like HTTP, FTP, SMTP etc.

Which interface should be implemented by all servlets?
Servlet interface should be implemented by all servlets.

What is the difference between HttpServlet and GenericServlet in Servlet API?
GenericServlet provides framework to create a Servlet for any protocol e.g. you can write Servlet to receive content from FTP, SMTP etc, while HttpServlet is built-in Servlet provided by Java for handling HTTP requests.

What is life cycle of Servlet?
The Web container is responsible for managing the servlet’s life cycle. The Web container creates an instance of the servlet and then the container calls the init() method. At the completion of the init() method the servlet is in ready state to service requests from clients.

The container calls the servlet’s service() method for handling each request by spawning a new thread for each request from the Web container’s thread pool.

Before destroying the instance the container will call the destroy() method. After destroy() the servlet becomes the potential candidate for garbage collection.
When servlet is loaded?
1. First request is made
2. Auto loading and Server starts up
3. There is a single instance that answers all requests concurrently which saves memory
4. Administrator manually loads.

When Servlet is unloaded?
1. Server shuts down
2. Administrator manually unloads

What is difference between GET and POST method in HTTP protocol?
1). GET method passes request parameter in URL String while POST method passes request parameter in request body.
2). GET request can only pass limited amount of data while POST method can pass large amount of data to server.
3). GET request can be bookmarked and cached unlike POST requests.
4). GET is mostly used for view purpose (e.g. SQL SELECT) while POST is mainly use for update purpose (e.g. SQL INSERT or UPDATE).

Can you override service method in servlet?
Yes. When we override service method in HttpServlet then call will go to service() method instead of doGet() or doPost() method.

When a request is made, the Sun Java System Web Server hands the incoming data to the servlet engine to process the request. The request includes form data, cookies, session information, and URL name-value pairs, all in a type HttpServletRequest object called the request object. Client metadata is encapsulated as a type HttpServletResponse object called the response object. The servlet engine passes both objects as the servlet's service() method parameters.

The default service() method in an HTTP servlet routes the request to another method based on the HTTP transfer method (POST, GET, and so on). For example, HTTP POST requests are routed to the doPost() method, HTTP GET requests are routed to the doGet() method.

This enables the servlet to perform different request data processing depending on the transfer method. Since the routing takes place in service(), there is no need to generally override service() in an HTTP servlet. Instead, override doGet(), doPost(), and so on, depending on the expected request type.

The automatic routing in an HTTP servlet is based simply on a call to request.getMethod(), which provides the HTTP transfer method. In a Sun Java System Web Server, request data is already preprocessed into a name-value list by the time the servlet sees the data, so simply overriding the service() method in an HTTP servlet does not lose any functionality. However, this does make the servlet less portable, since it is now dependent on preprocessed request data.

Override the service() method (for generic servlets) or the doGet() or doPost() methods (for HTTP servlets) to perform tasks needed to answer the request. Very often, this means collating the needed information (in the request object or in a JDBC result set object), and then passing the newly generated content to a JSP for formatting and delivery back to the client.

How can we create deadlock condition on our servlet?
Call doPost() method inside doGet() and doGet()method inside doPost().

Can you declare constructor inside Servlet class?
Yes, Servlet can have Constructor, but it's not the right way to initialize your Servlet. You need to use the init() method provided by the Servlet interface to initialize the Servlet correctly.

A servlet container creates a pool of multiple Servlets to serve multiple clients at the same time. They instantiate Servlet by calling the default no-argument constructor and suppose you have declared another constructor which takes a parameter e.g. LoginServlet(String username), than Java compiler will not add the default no-argument constructor and Servlet container will not able to initialize the Servlet. That's why it's important not to provide a constructor in Servlet, but if you do, make sure you also add a default constructor there for Servlet container.

When developer declared a parameterized constructor, default constructor is not added ( Java compiler doesn't add default no argument constructor, if there is a parametric constructor present in class), and if Servlet container e.g. Tomcat tries to instantiate a Servlet in order to serve the first request from client, it will throw "java.lang.InstantiationException: LoginServlet"

For initializing a servlet can we use a constructor in place of init()?
No, we can not use constructor for initializing a servlet, because a Servlet require ServletConfig object for initialization which is created by container as it also has reference of ServletContext object, which is also created by container.

Why super.init(config) is the first statement inside init(config) method?
This will be the first statement if we are overriding the init(config) method, by this way we will store the config object for future reference and we can use by getServletConfig() to get information about config object. Without doing this if we call the ServletConfig method will get NullPointerException.

What happens if you call destroy() from init() in java servlet?
The destroy() gets executed and then the servlet initialization gets completed. Ideally destroy() is not supposed to be called by the programmer. But, if it is invoked, it gets executed. The implicit question is, will the servlet get destroyed? Well the answer is NO, it will not.

destroy() method is not supposed to and will not destroy a java servlet. The meaning of destroy() in java servlet is, the content gets executed just before when the container decides to destroy the servlet. But if you invoke the destroy() method yourself, the content just gets executed and then the respective process continues.

What is a filter, and how does it work?
A filter is an object that performs filtering tasks on either the request to a resource (a servlet or static content), or on the response from a resource (from the Servlet or JSP before sending it back to client), or both.

Filters improve reusability by placing recurring tasks in the filter as a reusable unit. A good way to think of Servlet filters is as a chain of steps that a request and response must go through before reaching a Servlet, JSP, or static resource such as an HTML page in a Web application.

The filters can be used for caching and compressing content, logging and auditing, image conversions (scaling up or down etc), authenticating incoming requests, XSL transformation of XML content, localization of the request and the response, site hit count etc. The filters are configured through the web.xml file as follows:

< web-app >
< filter >
< filter-name >TestCountFilter< /filter-name >
< filter-class >test.TestCountFilter< /filter-class >
< /filter >
< filter-mapping >
< filter-name >TestCountFilter< /filter-name >
< url-pattern >/TespApp/*< /url-pattern >
< /filter-mapping >
< /web-app >

What are the important functions of filters?
  • Security check
  • Modifying the request or response
  • Data compression
  • Logging and auditing
  • Response compression
What is the significance of load-on-startup tag in web.xml?
By default the container does not initialize the servlets as soon as it starts up. It initializes a servlet when it receives a request for the first time for that servlet. This is called lazy loading. If < load-on-startup > 1 < /load-on-startup > is defined inside < servlet > < servlet >, then the servlet for which we have defined this tag will be initialized in starting when context is loaded before getting any request. It is called pre-initialization.

What is JSP?
JSP (Java ServerPages) is an extension of the Java Servlet technology. JSP is commonly used as the presentation layer for combining HTML and Java code.

While Java Servlet technology is capable of generating HTML with out.println("< html >...< /html >") statements, where out is a PrintWriter. This process of embedding HTML code with escape characters is cumbersome and hard to maintain. The JSP technology solves this by providing a level of abstraction so that the developer can use custom tags and action elements, which can speed up Web development and are easier to maintain.

Explain the life cycle methods of a JSP?
  • Pre-translated: Before the JSP file has been translated and compiled into the Servlet.
  • Translated: The JSP file has been translated and compiled as a Servlet.
  • Initialized: Prior to handling the requests in the service method the container calls the jspInit() to initialize the Servlet. Called only once per Servlet instance.
  • Servicing: Services the client requests. Container calls this method for each request.
  • Out of service: The Servlet instance is out of service. The container calls the jspDestroy() method. 
What is the jspInit() method?
The jspInit() method of the javax.servlet.jsp.JspPage interface is similar to the init() method of servlets. This method is invoked by the container only once when a JSP page is initialized. It can be overridden by a page author to initialize resources such as database and network connections, and to allow a JSP page to read persistent configuration data.

What is the _jspService() method?
The _jspService() method of the javax.servlet.jsp.HttpJspPage interface is invoked every time a new request comes to a JSP page. This method takes the HttpServletRequest and HttpServletResponse objects as its arguments. A page author cannot override this method, as its implementation is provided by the container.

What is the jspDestroy() method?
The jspDestroy() method of the javax.servlet.jsp.JspPage interface is invoked by the container when a JSP page is about to be destroyed. This method is similar to the destroy() method of servlets. It can be overridden by a page author to perform any cleanup operation such as closing a database connection.

What JSP lifecycle methods can I override?
You cannot override the _jspService() method within a JSP page. You can however, override the jspInit() and jspDestroy() methods within a JSP page. jspInit() can be useful for allocating resources like database connections, network connections, and so forth for the JSP page. It is good programming practice to free any allocated resources within jspDestroy().

What are implicit objects in JSP?
Implicit objects in JSP are the Java objects that the JSP Container makes available to developers in each page. These objects need not be declared or instantiated by the JSP author. They are automatically instantiated by the container and are accessed using standard variables; hence, they are called implicit objects. Below are the implicit objects available in JSP:
request, response, pageContext, session, application, out, config, page, exception

The implicit objects are parsed by the container and inserted into the generated servlet code. They are available only within the jspService method and not in any declaration.

How do you get ServletContext reference inside Servlet ?
Its easy to get reference of ServletContext in jsp using application implicit variable, but in Servlet is not available in HttpServletRequest until version 3.0. We need HttpSession object to retrieve ServletContext in any Servlet.

What is difference between ServletContext and ServletConfig in Java?
Both ServletContext and ServletConfig are basically configuration objects which are used by servlet container to initialize various parameter of web application. But they have a difference in terms of scope and availability.

ServletConfig : Its an interface in Servlet API and ServletConfig object represents or used to initialize single servlet in web application by servlet container. Inside deployment descriptor known as web.xml, we define Servlet initialization parameter related to that servlet inside < init-param> tag. Its a set of name /value pair. By using ServletConfig and combination of init-param you can configure any Servlet in J2EE environment.

ServletContext: It is even more important than ServletConfig and its one per web application, also known as Context. This object is common for all the servlet and they use this object to communicate with the servlet container to get the detail of whole web application or execution environment important thing to remember is, it represents a web application in single JVM.

By using ServletContext object you can share objects to any Servlet or JSP in whole web application.

1. ServletConfig object represent single servlet, where as ServletContext represent whole web application running on particular JVM and common for all the servlet.
2. ServletConfig is like local parameter associated with particular servlet. ServletContext is like global parameter associated with whole application.
3. ServletConfig is a name value pair defined inside the servlet section of web.xml file so it has servlet wide scope. Where as ServletContext has application wide scope so define outside of servlet tag in web.xml file.
4. getServletConfig() method is used to get the config object and getServletContext() method is  used to get the context object. 
How to set the context amd config parameters in web.xml?
To set config parameters:
< servlet >
     < display-name >GermanLogisticsServlet< /display-name >
     < servlet-name >GermanLogisticsServlet< /servlet-name >
     < init-param >
         < param-name >City< /param-name >
         < param-value >Kempten< /param-value >
     < /init-param >
< /servlet >

To access config parameters : getServletConfig().getInitParameter("City");

To set context parameters:
< web-app >
    < context-param >
        < param-name >Country< /param-name >
        < param-value >Germany< /param-value >
    < /context-param >
< /web-app >

To access context parameters in a JSP or Servlet : getServletContext().getInitParameter("Country");

How can you get the information about one servlet context in another servlet?
In context object, we can set the attribute which we want on another servlet and we can get that attribute using their name on another servlet.
Context.setAttribute ("logincontext", "value");
Context.getAttribute (logincontext);

What are JSP directives?
JSP directives are messages for the JSP engine. i.e. JSP directives serve as a message from a JSP page to the JSP container and control the processing of the entire page. They are used to set global values such as a class declaration, method implementation, output content type, etc.

They do not produce any output to the client. Directives are always enclosed within < %@...% > tag. e.g: page directive, include directive, etc.

In short, The jsp directives are messages that tells the web container how to translate a JSP page into the corresponding servlet.

There are three types of directives: page, include, taglib. 

What is page directive?
page directive provide attributes that gets applied to the entire JSP page.
A page directive is to inform the JSP engine about the headers or facilities that page should get from the environment. You may code page directives anywhere in your JSP page. By convention, page directives are coded at the top of the JSP page. Typically, the page directive is found at the top of almost all of our JSP pages.

What are the attributes of page directive?
There are thirteen attributes defined for a page directive of which the important attributes are as follows:
errorPage attribute tells the JSP engine which page to display if there is an error while the current page runs. The value of the errorPage attribute is a relative URL. The following directive displays myErrorPage.jsp when all uncaught exceptions are thrown:
< %@ page errorPage="myErrorPage.jsp" % >

isErrorPage attribute indicates that the current JSP can be used as the error page for another JSP. The value of isErrorPage is either true or false. The default value of the isErrorPage attribute is false. For example, the myErrorPage.jsp sets the isErrorPage option to true because it is supposed to handle errors:
< %@ page isErrorPage="true" % >

import attribute serves the same function as, and behaves like, the Java import statement. The value for the import option is the name of the package you want to import.

< %@ page import="java.sql.*" % >

To import multiple packages you can specify them separated by comma, e.g: < %@ page import="java.sql.*,java.util.*"  % >

info attribute lets you provide a description of the JSP. The following is a coding example:

< %@ page info="This JSP Page Written By K Himaanshu Shuklaa"  % >

isELIgnored attribute gives you the ability to disable the evaluation of Expression Language (EL) expressions which has been introduced in JSP 2.0

The default value of the attribute is true, meaning that expressions, ${...}, are evaluated as dictated by the JSP specification. If the attribute is set to false, then expressions are not evaluated but rather treated as static text.

< %@ page isELIgnored="false" % >

How to implement a thread-safe JSP page? What are the advantages and Disadvantages of using it?
JSPs can be thread-safe by having them implement the SingleThreadModel interface. This is done by adding 'isThreadSafe' in the the page directive, e.g:

< %@ page isThreadSafe="false" % >

With this, instead of a single instance of the servlet generated for your JSP page loaded in memory, we will have N instances of the servlet loaded and initialized, with the service method of each instance effectively synchronized.

We can typically control the number of instances (N) that are instantiated for all servlets implementing SingleThreadModel through the admin screen for our JSP engine.

What is the include directive?
The include directive is used to includes a file during the translation phase. This directive tells the container to merge the content of other external files with the current JSP during the translation phase. You may code include directives anywhere in your JSP page.

Include directive has only one attribute called file that specifies the name of the file to be included. The syntax of the include directive is: < %@ include file = "FileName" % >

The FileName in the include directive is actually a relative URL. If you just specify a FileName with no associated path, the JSP compiler assumes that the file is in the same directory as your JSP.

What is taglib Directive?
The JavaServer Pages API allows you to define custom JSP tags that look like HTML or XML tags and a tag library is a set of user-defined tags that implement custom behavior.

The taglib directive declares that your JSP page uses a set of custom tags, identifies the location of the library, and provides a means for identifying the custom tags in your JSP page.

The taglib directive has a syntax: < %@ taglib uri="uri" prefix="prefixOfTag"  >

Where the uri attribute value resolves to a location the container understands and the prefix attribute informs a container what bits of markup are custom actions.

What are the JSP standard actions?
The JSP standard actions affect the overall runtime behavior of a JSP page and also the response sent back to the client. They can be used to include a file at the request time, to find or instantiate a JavaBean, to forward a request to a new page, to generate a browser-specific code, etc.
  • jsp:include :- Includes a file at the time the page is requested
  • jsp:useBean :- Finds or instantiates a JavaBean
  • jsp:setProperty :- Sets the property of a JavaBean
  • jsp:getProperty :- Inserts the property of a JavaBean into the output
  • jsp:forward :- Forwards the requester to a new page
  • jsp:plugin :- Generates browser-specific code that makes an OBJECT or EMBED tag for the Java plugin
  • jsp:element :- Defines XML elements dynamically.
  • jsp:attribute :- Defines dynamically defined XML element's attribute.
  • jsp:body :- Defines dynamically defined XML element's body.
  • jsp:text :- Use to write template text in JSP pages and documents.
What is difference between include action and include directive in JSP?
When a request comes for JSP page, that JSP page first translated into Servlet class and then that servlet gets compiled and loaded into heap memory by the web container. Code written using JSP declaration e.g. < %! > goes into body of generated servlet as instance variable and all code from body goes into service() method of generated Servlet. In case of tomcat web-server these generated servlet files goes inside work directory.

In short, we can say JSP pages in three steps JSP page gets executed: Translation->Compilation->Execution. (JSP file will only be re-compiled only if there is a change in JSP file.)

Include directive in JSP
Include directive in JSP is used to import a static file or dynamic file e.g. including header and footer in JSP. Include directive is also called file include because resource to be included is specified using file attribute, e.g:

< %@ include file="header.jsp" % >

The code written in header.jsp will be included as it is in the jsp file which included it during JSP translation time and than merged code is get compiled to generate Servlet which is later used to server request.

Include action in JSP
Include action in JSP is another way of including a jsp file inside another jsp file. Included resource is specified using page attribute, e.g:

< jsp:include page="header.jsp" % >

header.jsp will be included during request time instead of translation time and any change in header.jsp will reflect immediately. Due to this nature include action is also called dynamic include in JSP. It also referred as page includes because of page attribute used to specify included resource.

Difference between include action and include directive:
  • include directive is static import while include action is dynamic import
  • Resource included by including directive is loaded during jsp translation time, while resource included by including action is loaded during request time.
  • Any change on included resource will not be visible in case of include directive until jsp file compiles again. While in the case of include again any change in included resource will be visible in next request.
What is the < jsp:useBean > standard action?
The < jsp:useBean > standard action first searches for an existing object (java bean) utilizing the id and scope variables. If an object is not found, it then tries to create the specified object.

< jsp:useBean id="name" class="package.class" / >

Once a bean class is loaded, you can use jsp:setProperty and jsp:getProperty actions to modify and retrieve bean properties.

Attributes of jsp:useBean are
  • class-Designates the full package name of the bean.
  • type-Specifies the type of the variable that will refer to the object.
  • beanName-Gives the name of the bean as specified by the instantiate () method of the java.beans.Beans class.

What is the < jsp:setProperty > standard action?
The setProperty action sets the properties of a Bean. The Bean must have been previously defined before this action. There are two basic ways to use the setProperty action:

< jsp:useBean id="myName" ... / >
< jsp:setProperty name="myName" property="someProperty" .../ >

In this case, the jsp:setProperty is executed regardless of whether a new bean was instantiated or an existing bean was found.

< jsp:useBean id="myName" ...  >
   < jsp:setProperty name="myName" property="someProperty" .../ >
< /jsp:useBean >

Attributes associated with setProperty action:
  • name :- Designates the bean whose property will be set. The Bean must have been previously defined.
  • property :- Indicates the property you want to set. A value of "*" means that all request parameters whose names match bean property names will be passed to the appropriate setter methods.
  • value :- The value that is to be assigned to the given property. The the parameter's value is null, or the parameter does not exist, the setProperty action is ignored.
  • param :- The param attribute is the name of the request parameter whose value the property is to receive. You can't use both value and param, but it is permissible to use neither.
What is the < jsp:getProperty > standard action?
getProperty action is used to retrieve the value of a given property and converts it to a string, and finally inserts it into the output.

The getProperty action has only two attributes 'name' and 'property':

< jsp:useBean id="myName" ... / >
< jsp:getProperty name="myName" property="someProperty" .../ >

Where, 'name' is the name of the Bean that has a property to be retrieved. The Bean must have been previously defined. and 'property' is the property attribute is the name of the Bean property to be retrieved.

What are JSP Scripting elements?
The scripting elements provides the ability to insert java code inside the jsp. There are three types of scripting elements, scriptlet, expression and declaration.

What is a scriptlet in JSP?
A scriptlet tag is used to execute java source code in JSP. e.g:

< % java code %>

You can write XML equivalent of the above syntax as follows:

< jsp:scriptlet >
   java code
< /jsp:scriptlet >

What is JSP Declarations?
A declaration declares one or more variables or methods that you can use in Java code later in the JSP file. You must declare the variable or method before you use it in the JSP file. The code written inside the jsp declaration tag is placed outside the service() method of auto generated servlet. So it doesn't get memory at each request.
< %! int a, b, c; % >
< %! Circle a = new Circle(2.0); % >

Difference between JSP Scriptlet tag and Declaration tag?
  • The jsp scriptlet tag can only declare variables not methods. The jsp declaration tag can declare variables as well as methods.
  • The declaration of scriptlet tag is placed inside the _jspService() method.    The declaration of jsp declaration tag is placed outside the _jspService() method.
What is JSP Expression?
A JSP expression element contains a scripting language expression that is evaluated, converted to a String, and inserted where the expression appears in the JSP file. Because the value of an expression is converted to a String, you can use an expression within a line of text, whether or not it is tagged with HTML, in a JSP file.

The expression element can contain any expression that is valid according to the Java Language Specification but you cannot use a semicolon to end an expression. e.g:

< %= expression %>

Or you can write XML equivalent of the above syntax as follows:

< jsp:expression >
< /jsp:expression >

How do you define application wide error page in JSP?
We can define error pages in Java web application in two ways, using tag in web.xml and other is by using error page JSP which uses isErrorpage to declare that this jsp page can be used as error page.

Page Specific Error page in JSP : By setting 'errorpage' attribute on page directive of JSP, we can define an error page for any particular JSP. After that if any unhandled Exception thrown from that JSP, this error page will be invoked. e.g:
< %@ page errorPage="error.jsp"% >

That means, if any exception occurs in userlogin.jsp then error.jsp is show. In order to make error.jsp as a error page, we need to mark 'isErrorPage' attribute as true. e.g:
<%@ page isErrorPage="true"%>

Application wide Error page in Java web application: It is called application wide error page or default/general error page because its applicable to whole web application instead of any particular servlet or JSP. This error page is defined in web.xml by using tag < error-page >. This tag allows you to define custom error message based upon HTTP error code or any Java Exception. you can define a default error message for all exception by specifying < exception-type > as java.lang.Throwable and it would be applicable to all exception thrown form any Servlet or JSP from web application. e.g:

< error-page >
        < exception-type >java.lang.Throwable< /exception-type >
        < location >/error.html< /location >
< /error-page >
< error-page >
    < error-code >404< /error-code >
    < location >/page-not-found-error.htm< /location >
< /error-page >

What is Request Dispatcher?
RequestDispatcher interface is used to forward the request to another resource that can be HTML, JSP or another servlet in same application. We can also use this to include the content of another resource to the response. This interface is used for inter-servlet communication in the same context.

Difference between SendRedirect() and Forward() in JSP Servlet
1). Forward transfer the request to other resource within the same server for further processing. In case of sendRedirect request is transfer to another resource to different domain or different server for futher processing.
2). In case of forward Web container handle all process internally and client or browser is not involved. When you use SendRedirect container transfers the request to client or browser so url given inside the sendRedirect method is visible as a new request to the client.
3). When forward is called on requestdispather object we pass request and response object so our old request object is present on new resource which is going to process our request. In case of SendRedirect call old request and response object is lost because it’s treated as new request by the browser.
4). Visually we are not able to see the forwarded address, its is transparent. Where as in address bar we are able to see the new redirected address it’s not transparent.
5). Using forward () method is faster then send redirect. SendRedirect is slower because one extra round trip is required beasue completely new request is created and old request object is lost.Two browser request requird.
6). When we redirect using forward and we want to use same data in new resource we can use request.setAttribute () as we have request object available. But in sendRedirect if we want to use we have to store the data in session or pass along with the URL.

Forward() is declared in RequestDispatcher Interface.
Method Signature: forward(ServletRequest request, ServletResponse response)

RequestDispatcher rd = request.getRequestDispatcher("welcomeToGermany.jsp");
rd.forward(request, response);


RequestDispatcher rd = servletContext.getRequestDispatcher("/welcomeToGermany.jsp");
rd.forward(request, response);

SendRedirect ()
is declared in HttpServletResponse Interface.
Method Signature: void sendRedirect(String url)


What is servlet attributes and their scope?
Servlet attributes are used for inter-servlet communication, we can set, get and remove attributes in web application. There are three scopes for servlet attributes – request scope, session scope and application scope.

ServletRequest, HttpSession and ServletContext interfaces provide methods to get/set/remove attributes from request, session and application scope respectively.

Servlet attributes are different from init parameters defined in web.xml for ServletConfig or ServletContext.

What is difference between PrintWriter and ServletOutputStream?
PrintWriter is a character-stream class whereas ServletOutputStream is a byte-stream class. We can use PrintWriter to write character based information such as character array and String to the response whereas we can use ServletOutputStream to write byte array data to the response.

We can use ServletResponse getWriter() to get the PrintWriter instance whereas we can use ServletResponse getOutputStream() method to get the ServletOutputStream object reference.

Can we get PrintWriter and ServletOutputStream both in a servlet?
We can’t get instances of both PrintWriter and ServletOutputStream in a single servlet method, if we invoke both the methods; getWriter() and getOutputStream() on response; we will get java.lang.IllegalStateException at runtime with message as other method has already been called for this response.

What is called Session Tracking? Why it is needed?
Session tracking is used to maintain a state on the series of requests from the same user for a given period of time. Every HTTP request needs to be captured by HTTP protocol and for that, state is captured. Tracking of state is called session tracking.

What are the types of Session Tracking ?

1. URL rewriting: In this method of session tracking, some extra data is appended at the end of the URL, which identifies the session. This method is used for those browsers which do not support cookies or when the cookies are disabled by the user.
2. Hidden Form Fields: This method is similar to URL rewriting. New hidden fields are embedded by the server in every dynamically generated form page for the client. When the form is submitted to the server the hidden fields identify the client.
3. Cookies: Cookie refers to the small amount of information sent by a servlet to a Web browser. Browser saves this information and sends it back to the server when requested next. Its value helps in uniquely identifying a client.
4. Secure Socket Layer (SSL) Sessions

What are the advantages of cookies?
Cookies are used to store long term information that can be maintained without server interaction. Small and Medium size data are kept in a queue.

What is URL rewriting?
URL rewriting is one of the methods of session tracking in which additional data is appended at the end of each URL. This additional data identifies the session.

Difference between URL-rewriting URL-encoding in Servlet JSP
URL-rewriting is a technique to maintain user session if cookies are not enabled on client browser or browser doesn't support cookie, while URL-encoding is a way to pass string to server containing special characters  by converting special characters like space into some other characters like +.

People often confuse between URL encoding and URL rewriting because of there names which sounds quite similar for new guys but functionality wise they are totally different to each other, Also servlet encodeURL() method adds more confusion because its sounds like its used for URL Encoding but indeed used for URL Rewriting.

1). java.servlet.http.HttpServletResponse methods encodeURL(String url) and encodeRedirectURL(String URL) is used to embed SesssionID on URL to support URL-rewriting. The logic to include sessionID is in method itself and it doesn't embed sessionID, if browser supports cookies or session maintenance is not required. In order to implement a robust session tracking all URL from Servlet and JSP should have session id embedded on it.

In order to implement URL-rewriting in JSP you can use use JSTL core tag all URL passed to it will automatically be URL-rewriting if browser doesn't support cookies. While java.net.URLEncoder.encode() and java.net.URLDecoder.decode()is used to perform URL Encoding and decoding which replace special character from String to another character. This method uses default encoding of system and also deprecated instead of this you can use java.net.URLEncoder.encode(String URL, String encoding) which allows you to specify encoding. as per W3C UTF-8 encoding should be used to encode URL in web application.

2) In URL rewriting session id is appended to URL and in case of URL-encoding special character replaced by another character.

What is JSESSIONID in Java? When does JSESSIONID gets created ?
HTTP is a stateless protocol there is no way for Web Server to relate two separate requests coming from the same client and Session management is the process to track user session using different session management techniques like Cookies and URL Rewriting.

JSESSIONID is a cookie generated by Servlet containers like Tomcat and is used for session management in J2EE web application for HTTP protocol.

When a web server use a cookie for session management. it creates and sends JSESSIONID cookie to the client and then the client sends it back to the server in subsequent HTTP requests.

In Java J2EE application container is responsible for Session management, when a user first time access your web application, session is created based on whether its accessing HTML, JSP or Servlet.

If user request is served by Servlet than session is created by calling request.getSession(true) method. It accepts a boolean parameter which instruct to create session if its not already existed. If you pass 'false' in getSession() method then it will either return null(if no session is associated with this user) or return the associated HttpSession object.

If HttpRequest is for JSP page than Container automatically creates a new Session with JSESSIONID, if this feature is not disabled explicitly by using page directive <  %@ page session="false" % >.

In case of HTML access, no user session is created. If  client has disabled cookie than Container uses URL rewriting for managing session on which jsessionid is appended into URL.

When HTTP session is invalidated(), mostly when the user logged off, old JSESSIONID destroyed and a new JSESSIONID is created when the user further login.

How can you prevent the output of your JSP or Servlet pages from being cached by the browser?
We will need to set the appropriate HTTP header attributes to prevent the dynamic content output by the JSP page from being cached by the browser. We need to add below scriptlet at the beginning of JSP pages to prevent them from being cached at the browser. We need both the statements to take care of some of the older browser versions.

< % response.setHeader("Cache-Control","no-store"); //HTTP 1.1
response.setHeader("Pragma\","no-cache"); //HTTP 1.0
response.setDateHeader ("Expires", 0); //prevents caching at the proxy server
% >

How can you set variable in application scope in Servlet, so that it can be shared among sessions?
servletContext is used to store the global data which is going to share through out the application. This is not thread safe.
Suppose, you have two Servlet's Servlet1 and Servlet2. In init() method of Servlet1, we set USER_NAME as 'Matthew Langford Perry',
getServletContext().setAttribute("USER_NAME", "Matthew Langford Perry");

In doGet(), we are printing it.
PrintWriter out = response.getWriter();
out.println("USER_NAME in Servlet1="+getServletContext().getAttribute("USER_NAME"));

Now we create Servlet2, and in doGet(), we first print the USER_NAME from context and then update it.
PrintWriter out = response.getWriter();
out.println("Getting the USER_NAME from Context="+getServletContext().getAttribute("USER_NAME"));
getServletContext().setAttribute("USER_NAME", "Matthew Perry");
out.println("After changing USER_NAME in Context="+getServletContext().getAttribute("USER_NAME"));

When you run Servlet1, for the first time it will print:
USER_NAME in Servlet1=Matthew Langford Perry

Now run Servlet2, it will print:
Getting the USER_NAME from Context=Matthew Langford Perry
After changing USER_NAME in Context=Matthew Perry

Since init() is called only once, so if you run Servlet1 again it wil print:
USER_NAME in Servlet1=Matthew Perry

-K Himaanshu Shuklaa..

October 03, 2016

Producer Sheel Kumar scores big with Pink..

Producer Sheel kumar has done it again with his recent film Pink, that starred the legendary actor Amitabh Bachchan and host of new stars like Taapsee Pannu and Angad Bedi. The movie is a success with it earning over 50 crores in the first 10 days at the box office. The movie is currently in its second week is still going strong. Pink’s director Soojit Sircar’s faith was well placed considering the movie’s stellar performance at the box office which is another feather in the cap of Sheel Kumar who has co-produced popular movies like Madras Cafe and Rocky Handsome.

Screening of short periodic film '1869'

On 1st October 2016, Inorbit Mall witnessed a huge turnout for the screening of '1869' – India's first period short film. Attendees included personalities like Directors Samar Saikh, Sandeep Modi & Prashant Singh, writer Sanyukta Chawla, Cinematographer Himman Dhamija, Producers Saurabh Malhotra & Faisal Malik, Associate Director at NFDC Film Bazaar Maitreyee Dasgupta, President at Rediffusion Y&R Mr. Dhunji Wadia, Actors Anupriya Goenka, Tanvir Singh, Aayushi Lahiri, Vaibhav Raj Gupta and Vikram Kochhar among others.

Role of homeopathy in treating chronic diseases and terminally ill patients..

"Wonder Healing Process Of Homeopathy" organised by Humanitarian Welfare And Research Foundation on 2nd October 2016 was a successful afternoon where doctors discussed on a Medical Symposium about Chronic diseases. Present were Dr. Abdequaem Chimthanwala MD Homeopathy (London) and Dr. Akash Khobragade associate professor J.J.Hospital.

#MunnaMichael : Tiger Shroff pays an 'ABS'tatic tribute to MJ

Tiger Shroff, who is a die-hard Michael Jackson fan has expressed his desire in one of the interview that he wants to play MJ in his biopic. That plan has to wait for now. Nevertheless, in the meanwhile the Heropanti actor will be seen playing a street kid, who’s a huge fan of the late pop-star in 'Munna Michael'.

October 01, 2016

Java Thread Interview Questions & Answers..

What is Thread in Java?
Thread in Java is a light weight process and represent an independent path of execution. It's way to take advantage of multiple CPU available in a machine. By employing multiple threads you can speed up CPU bound task.

E.g, if one thread takes 100 milliseconds to do a job, you can use 10 thread to reduce that task into 10 milliseconds. Java provides excellent support for multithreading at the language level, and it's also one of the strong selling points.

What is the difference between Thread and Process in Java?

  • One process can contain multiple threads, which means the thread is a subset of Process.
  • Two process runs on different memory space, but all threads share same memory space. Don't confuse this with stack memory, which is different for the different thread and used to store local data to that thread. 
  • Threads can directly communicate with other threads of its process; processes must use interprocess communication to communicate with sibling processes. 

What is a daemon thread?
Daemon threads are sometimes reffered as "service" threads. These are threads that normally run at a low priority and provide a basic service to a program or programs when activity on a machine is reduced. e.g: a daemon thread is provided by JVM, which is continuously running is the garbage collector thread.

How do you implement Thread in Java?
There are two ways of implementing threading in Java :
1) By extending java.lang.Thread class
2) By implementing java.lang.Runnable interface

Since Thread class itself implement Runnable, we can override run() method either by extending Thread class or just implementing Runnable interface.

public class MyThread extends Thread{
   public void run(){
      System.out.println("My Thread Running: " + Thread.currentThread().getName());
Thread mythread = new MyThread();

public class MyRunnable implements Runnable{        
public void run(){
       System.out.println("My Runnable Running: " + Thread.currentThread().getName());

//An instance of java.lang.Thread represent a thread but it needs a task to execute, which is an instance of interface java.lang.Runnable.
Thread myrunnable = new Thread(new MyRunnable(),"mythreadwithrunnable");

What is the difference between start() and run() method of Thread class?
When a program calls start() method, a new Thread is created and code inside run() method is executed in new Thread. If you call run() method directly, no new Thread will be created and code inside run() will be executed on current Thread.

Another difference between start vs run in Java thread is that you can not call start() method twice on thread object. Once started, second call of start() will throw IllegalStateException in Java while you can call run() method twice.

What is the difference between Runnable and Callable in Java?
1. Runnable is there from JDK 1.0 while Callable was added on JDK 1.5.
2. Runnable interface has run() method to define task while Callable interface uses call() method for task definition.
3. run() method does not return any value, it's return type is void while call method returns  java.lang.Object type. The Callable interface is a generic parameterized interface and Type of value is provided when an instance of Callable implementation is created.
4. One more difference is that the Callable interface can throw checked exception, while Runnable can't [run() does not throw any checked exception)

What is the difference between CyclicBarrier and CountDownLatch in Java?
The main difference between CountDownLatch & CyclicBarrier is that you can not re-use CountDownLatch once count reaches to zero, but you can reuse same CyclicBarrier even after barrier is broken. (For more info read : Difference between CountDownLatch & CyclicBarrier in Java)

What is volatile variable in Java?
volatile variable in Java is a special variable which is used to signal threads, a compiler that this particular variables value are going to be updated by multiple threads inside Java application.

When we make a variable, we ensures that its value should always be read from main memory and thread should not use cached value of that variable from their own stack.

The volatile keyword can only be applied to a variable, it can not be applied to class or method. using volatile keyword along with class and method is a compiler error.

When to use Volatile variable in Java?
1) Any variable which is shared between multiple threads should be made variable, in order to ensure that all thread must see the latest value of the volatile variable.
2) A signal to compiler and JIT to ensure that compiler does not change ordering or volatile variable and moves them out of synchronized context.
3) You want to save the cost of synchronization as volatile variables are less expensive than synchronization.

What is race condition in Java?
Race conditions occurs when two thread operate on same object without proper synchronization and there operation interleaves on each other.

It is a situation in which two or more threads or processes are reading or writing some shared data, and the final result depends on the timing of how the threads are scheduled.

Race conditions can lead to unpredictable results and subtle program bugs. A thread can prevent this from happening by locking an object. When an object is locked by one thread and another thread tries to call a synchronized method on the same object, the second thread will block until the object is unlocked.

A race condition occurs due to race between multiple threads, if a thread which is supposed to execute first lost the race and executed second, behaviour of code changes, which surface as non-deterministic bugs. This is one of the hardest bugs to find and re-produce because of random nature of racing between threads.

How to stop a thread in Java?
It's easy to start a thread in Java because you have a start() method, but it's difficult to stop the thread because there is no working stop() method. There was some control methods in JDK 1.0 e.g. stop(), suspend() and resume() which was deprecated in later releases due to potential deadlock threats

Programmers mainly rely on the fact that thread stops automatically as soon as they finish execution of run() or call() method. To manually stop, programmers either take advantage of volatile boolean variable and check in every iteration if run method has loops or interrupt threads to abruptly cancel tasks. e.g:

class Server implements Runnable{
    private volatile boolean isforexit = false;   
    public void run() {
            System.out.println("Server is running!!");
        System.out.println("Server is stopped!!");
    public void stop(){
        isforexit = true;
public class MyThreadStopTest {
    public static void main(String args[]) throws InterruptedException {
        Server myServer = new Server();

        Thread t1 = new Thread(myServer, "T1");

What happens when an Exception occurs in a thread?
If exception is not caught thread will die, else if an uncaught exception handler is registered then it will get a call back.

What is the use of Thread.UncaughtExceptionHandler interface?
Thread.UncaughtExceptionHandler is an interface, defined as nested interface for handlers invoked when a Thread abruptly terminates due to an uncaught exception.

As we know, Checked exceptions must be specified in the throws clause of a method or caught inside them. Where as, Unchecked exceptions don’t have to be specified or caught.

When a checked exception is thrown inside the run() method of a Thread object, we have to catch and treat it accordingly, because the run() method doesn’t accept a throws clause. But when an unchecked exception is thrown inside the run() method of a Thread object, the default behavior is to write the stack trace in the console (or log it inside error log file) and exit the program.

However, with UncaughtExceptionHandler interface, Java provides us with a mechanism to catch and treat the unchecked exceptions thrown in a Thread object to avoid the program ending.

When a thread is about to terminate due to an uncaught exception, the Java Virtual Machine will query the thread for its UncaughtExceptionHandler using Thread.getUncaughtExceptionHandler() and will invoke the handler's uncaughtException method, passing the thread and the exception as arguments. If a thread has not had its UncaughtExceptionHandler explicitly set, then its ThreadGroup object acts as its UncaughtExceptionHandler. If the ThreadGroup object has no special requirements for dealing with the exception, it can forward the invocation to the default uncaught exception handler.

1). You need to implement UncaughtExceptionHandler:
class MyExceptionHandler implements UncaughtExceptionHandler
   public void uncaughtException(Thread t, Throwable e)
      System.out.printf("An exception has been captured. Thread: %s\n", t.getId());
      System.out.printf("Exception: %s: %s\n", e.getClass().getName(), e.getMessage());
      System.out.printf("Stack Trace: \n");
      System.out.printf("Thread status: %s\n", t.getState());
      new Thread(new Task()).start();

2). Set UncaughtExceptionHandler inside run() method:
class Task implements Runnable
   public void run()
      Thread.currentThread().setUncaughtExceptionHandler(new MyExceptionHandler());

What are the different states of a thread's lifecycle?
  • Runnable:waiting for its turn to be picked for execution by the thread scheduler based on thread priorities.
  • Running: The processor is actively executing the thread code. It runs until it becomes blocked, or voluntarily gives up its turn with this static method Thread.yield(). Because of context switching overhead, yield() should not be used very frequently.
  • Waiting: A thread is in a blocked state while it waits for some external processing such as file I/O to finish.
  • Sleeping: Java threads are forcibly put to sleep (suspended) with this overloaded method: Thread.sleep(milliseconds), Thread.sleep(milliseconds, nanoseconds);
  • Blocked on I/O: Will move to runnable after I/O condition like reading bytes of data etc changes.
  • Blocked on synchronization: Will move to Runnable when a lock is acquired.
  • Dead: The thread is finished working.
What is the difference between yield and sleeping?
Both yield and sleep are declared on java.lang.Thread class and doesn't release any lock held by the thread.

yield() method pauses the currently executing thread temporarily for giving a chance to the remaining waiting threads of the same priority to execute. If there is no waiting thread or all the waiting threads have a lower priority then the same thread will continue its execution. The yielded thread when it will get the chance for execution is decided by the thread scheduler whose behavior is vendor dependent.

sleep() allows the thread to go to sleep state for x milliseconds.

When a task invokes yield(), it changes from running state to runnable state. When a task invokes sleep(), it changes from running state to waiting/sleeping state.

How do you share data between two thread in Java?
wait and notify methods in Java are used for inter-thread communication i.e. if one thread wants to tell something to another thread, it uses notify() and notifyAll() method of java.lang.Object.

Classical example of wait and notify method is Producer Consumer design pattern, where One thread produce and put something on shared bucket, and then tell other thread that there is an item for your interest in shared object, consumer thread than pick than item and do his job, without wait() and notify(), consumer thread needs to be busy checking, even if there is no change in state of shared object.

This brings an interesting point on using wait and notify mechanism, a call to notify() happens, when thread changed state of shared object i.e. in this case producer change bucket from empty to not empty, and consumer change state from non-empty to empty.

Also wait and notify method must be called from synchronized context. A waiting thread may woke up, without any change in it's waiting condition due to spurious wake up. e.g: if a consumer thread, which is waiting because shared queue is empty, gets wake up due to a false alarm and try to get something from queue without further checking whether queue is empty or not than unexpected result is possible.

What is the difference between notify and notifyAll in Java?
notify and notifyAll is that notify method will only notify one Thread and notifyAll method will notify all Threads  which are waiting on that monitor or lock.

When you call notify only one of waiting for the thread will be woken and it's not guaranteed which thread will be woken, it depends on upon Thread scheduler.

While if you call notifyAll method, all threads waiting on that lock will be woken up, but again all woken thread will fight for lock before executing remaining code. That's why wait is called on loop because if multiple threads are woken up, the thread which will get lock will first execute and it may reset waiting for condition, which will force subsequent threads to wait.

Why wait, notify and notifyAll are not inside thread class? 
Java provides lock at object level not at thread level thats why wait, notify and notifyAll methods are defined in Object class. Every object has lock, which is acquired by thread. Now if thread needs to wait for certain lock it make sense to call wait() on that object rather than on that thread.

Had wait() method declared on Thread class, it was not clear that for which lock thread was waiting. In short, since wait, notify and notifyAll operate at lock level, it make sense to defined it on object class because lock belongs to object.

Why wait and notify method are called from synchronized block?

Every object created in Java has one associated monitor (mutually exclusive lock). Only one thread can own a monitor at any given time.

For achieving synchronization in Java this monitor is used. When any thread enters a synchronized method/block it acquires the lock on the specified object. When any thread acquires a lock it is said to have entered the monitor. All other threads which need to execute the same shared piece of code (locked monitor) will be suspended until the thread which initially acquired the lock releases it.

wait method tells the current thread (thread which is executing code inside a synchronized method or block) to give up monitor and go to waiting state.

notify method wakes up a single thread that is waiting on this object's monitor, where as notifyAll method wakes up all the threads that called wait( ) on the same object.

Any method or a block of code, if not qualified with the keyword synchronized can be executed by more than one thread at any given time as object's monitor(lock) is not in the picture. Where as when a method is synchronized (or there is a synchronized block) only a single thread who has acquired the object's monitor can access the code.

Since wait method is about thread releasing the object's lock and go to waiting state, where as notify/notifyAll methods are about notifying the thread(s) waiting for the object's lock. So, wait(), notify() and notifyAll() methods (as mentioned above) should be invoked on an object only when the current thread has already acquired the lock on an object.

If you don't call them from synchronized context, your code will throw IllegalMonitorStateException. A more subtle reason is to avoid the race condition between wait and notify calls.

What is the difference between the interrupted() and isInterrupted() method in Java?
In simple words, if you use interrupted, you're asking "Have I been interrupted since the last time I asked?". Where as isInterrupted tells you whether the thread you call it on is currently interrupted.

The interrupted() method is a class (static) method that always checks the current thread and clears the interruption flag. A second call to interrupted() will return false.

The isInterrupted() method is an instance method, it reports the status of the thread on which it is invoked. Also, it does not clear the interruption flag. If the flag is set, it will remain set after calling this method.

What is the difference between wait() and sleep()?
  • The wait() method belongs to java.lang.Object class, thus can be called on any Object. The sleep() method belongs to java.lang.Thread class, thus can be called on Threads.
  • The wait() method can only be called from Synchronized context i.e. using synchronized block or synchronized method. The sleep() method can be called from any context.
  • The wait() method releases the lock on an object and gives others chance to execute. The sleep() method does not releases the lock of an object for specified time or until interrupt.
  • A waiting thread can be awake by notify() or notifyAll() method. A sleeping can be awaked by interrupt or time expires.

What is thread pool?
We all know, creating a thread is expensive in terms of time and resource. If we create thread at time of request processing it will slow down our response time, also there is only a limited number of threads a process can create.

A Thread Pool gives us an option to avoid these issues. When a application starts-up, a pool of threads are created and the threads are reused for request processing. This pool of thread is known as 'thread pool' and threads are known as 'worker thread'.

From JDK 1.5 release, Java API provides Executor framework, which allows you to create different types of thread pools e.g. single thread pool, which process one task at a time, fixed thread pool (a pool of fixed number of threads) or cached thread pool (an expandable thread pool suitable for applications with many short lived tasks).

How do you check if a Thread holds a lock or not?
holdsLock() method from java.lang.Thread, it returns true if and only if the current thread holds the monitor lock on the specified object.

What is use of synchronized keyword?
Synchronized keyword provides a lock on the object and thus prevents race condition and can be applied to static/non-static methods or a block of code. Only one thread at a time can access synchronized methods and if there are multiple threads trying to access the same method then other threads have to wait for the execution of method by one thread. 

What happens when I make a static method as synchronized?
Synchronized static methods have a lock on the class "Class", so when a thread enters a synchronized static method, the class itself gets locked by the thread monitor and no other thread can enter any static synchronized methods on that class. This is unlike instance methods, as multiple threads can access "same synchronized instance methods" at same time for different instances.

Can we synchronize the run method? If yes then what will be the behavior?
Yes, the run method of a runnable class can be synchronized. If you make run method synchronized then the lock on runnable object will be occupied before executing the run method. In case we start multiple threads using the same runnable object in the constructor of the Thread then it would work. But until the 1st thread ends the 2nd thread cannot start and until the 2nd thread ends the next cannot start as all the threads depend on lock on same object.

Can we synchronize the constructor of a Java Class?
As per Java Language Specification, constructors cannot be synchronized because other threads cannot see the object being created before the thread creating it has finished it. There is no practical need of a Java Objects constructor to be synchronized, since it would lock the object being constructed, which is normally not available to other threads until all constructors of the object finish.

What is busy spin in a multi-threaded environment? or What is Busy Spinning?
It is one of the interesting multithreading question for senior Java programmers.

Busy spinning is a waiting strategy, in which one thread repeatedly checks to see if a condition is true instead of calling wait or sleep method and releasing CPU. It simply eats up the computer cycle because one thread keeps on looping continuously waiting for another thread to signal.

By not releasing the CPU or suspending the thread, your thread retains all the cached data and instruction, which may be lost if the thread was suspended and resumed back in a different core of CPU.

  System.out.println("waiting!! waiting!!");

What is ThreadLocal variable in Java?
Like instance variable is per instance, ThreadLocal variable is per thread. Since class is expensive, its not good to use it in local scope, which requires separate instance on each invocation.

What is thread pool?
We all know, creating a thread is expensive in terms of time and resource. If we create thread at time of request processing it will slow down our response time, also there is only a limited number of threads a process can create.

A Thread Pool gives us an option to avoid these issues. When a application starts-up, a pool of threads are created and the threads are reused for request processing. This pool of thread is known as 'thread pool' and threads are known as 'worker thread'.

What is the Java Thread Executor Framework?
Executor Framework in java has been introduced in JDK 5. It handles creation of thread, creating the thread pool and checking health while running and also terminates if needed.

Java API provides Executor framework, which allows you to create three different types of thread pools:
1.Executor.newCachedThreadPool: Creates a thread pool of unlimited size, but if threads get freed up, they are reused
2.Executor.newFixedThreadPool: Create a thread pool of fixed size, if pool is exhausted, tasks must wait till a thread becomes free
3.Executor.newSingleThreadExecutor: Creates only a single thread, tasks are executed sequentially form the queue

How to terminate a thread in Executor Framework in java?
When you are done using the ExecutorService you should shut it down, so the threads do not keep running.

e.g, if your application is started via a main() method and your main thread exits your application, the application will keep running if you have an active ExexutorService in your application. The active threads inside this ExecutorService prevents the JVM from shutting down.

To terminate the threads inside the ExecutorService you call its shutdown() method. The ExecutorService will not shut down immediately, but it will no longer accept new tasks, and once all threads have finished current tasks, the ExecutorService shuts down. All tasks submitted to the ExecutorService before shutdown() is called, are executed.

If you want to shut down the ExecutorService immediately, you can call the shutdownNow() method. This will attempt to stop all executing tasks right away, and skips all submitted but non-processed tasks. There are no guarantees given about the executing tasks. Perhaps they stop, perhaps the execute until the end. It is a best effort attempt.

What is the role of Executors.unconfigurableExecutorService in Executor Framework?
The unconfigurableExecutorService method in java executor returns an object that delegates all methods of ExecutorService to the given executor so that any other method cannot accessed by cast.

What is the role of ExecutorService in Java?
The java.util.concurrent.ExecutorService interface represents an asynchronous execution mechanism which is capable of executing tasks in the background. An ExecutorService is thus very similar to a thread pool. In fact, the implementation of ExecutorService present in the java.util.concurrent package is a thread pool implementation. e.g:

ExecutorService executorService = Executors.newFixedThreadPool(10);
executorService.execute(new Runnable() {
    public void run() {
        System.out.println("Asynchronous task");

First an ExecutorService is created using the newFixedThreadPool() factory method. This creates a thread pool with 10 threads executing tasks.

Second, an anonymous implementation of the Runnable interface is passed to the execute() method. This causes the Runnable to be executed by one of the threads in the ExecutorService

What is the role of FutureTask and Future in java?

FutureTask is base concrete implementation of Future interface and provides asynchronous processing. It contains the methods to start and cancel a task and also methods that can return the state of the FutureTask as whether it’s completed or cancelled.

We need a callable object to create a future task and then we can use Java Thread Pool Executor to process these asynchronously.

A FutureTask can be used to wrap a Callable or Runnable object. Because FutureTask implements Runnable, a FutureTask can be submitted to an Executor for execution.
How to use Callable and Future in Java?
The run() method of Runnable interface does not return any value, so if you need to get a value back from the now-completed task, you must use a method outside the interface and wait for some kind of notification message that the task completed. e.g:
Runnable runnable = ...;
Thread t = new Thread(runnable);
String outValue = callMethodToGetTheValue();

With Callable interface (which was introduced in J2SE 5.0) we can get the value by calling call() method. The call() can return an Object or, more specifically, any type that is introduced in the generalized form.

public interface Callable< V  >   {
     V call() throws Exception;

We cannot pass a Callable into a Thread to execute, instead ExecutorService is used to execute the Callable object. The service accepts Callable objects to run by way of the submit() method:

< T  >   Future< T  >   submit(Callable< T  >   task)

As the method definition shows, submitting a Callable object to the ExecutorService returns a Future object. The get() method of Future will then block until the task is completed. This is the equivalent of the join() call. Actually, it is the equivalent of both the join() call and the get value call as get() returns the value calculated by the Callable instance.

import java.util.*;
import java.util.concurrent.*;
public class CallableTest {

public static class WordLengthCallable implements Callable {
    private String word;
    public WordLengthCallable(String word) {
      this.word = word;
    public Integer call() {
      return Integer.valueOf(word.length());

public static void main(String args[]) throws Exception {
    String[] strArray = new String[2];
    strArray[0] = "Mariam";
    strArray[1] = "Donald";
    ExecutorService pool = Executors.newFixedThreadPool(3); // Executors.newSingleThreadExecutor();
    Set< Future< Integer  >    >   set = new HashSet< Future< Integer  >    >  ();
    for (String word: strArray) {
      Callable< Integer  >   callable = new WordLengthCallable(word);
      Future< Integer  >   future = pool.submit(callable);
    int sum = 0;
    for (Future< Integer  >   future : set) {
      sum += future.get();
    System.out.print("The sum of lengths is :"+ sum);

-K Himaanshu Shuklaa..
RSSChomp Blog Directory