Friday, April 18, 2014

Why wait, notify and notifyAll is defined in Object Class in Java


Here are some thoughts on why they should not be in Thread class which make sense to me :


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

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

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

Friday, June 28, 2013

Bean lifecycle in Spring framework

  • The spring container finds the bean’s definition from the XML file and instantiates the bean.
  • Using the dependency injection, spring populates all of the properties as specified in the bean definition.
  • If the bean implements the BeanNameAware interface, the factory calls setBeanName() passing the bean’s ID.
  • If the bean implements the BeanFactoryAware interface, the factory calls setBeanFactory(), passing an instance of itself.
  • If there are any BeanPostProcessors associated with the bean, their postProcessBeforeInitialization() methods will be called.
  • If an init-method is specified for the bean, it will be called.
  • Finally, if there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methods will be called.

Sunday, September 9, 2012

Increase Java Heap Memory for Maven 2

The heap size of the JVM used by Maven can be changed using the environment variable MAVEN_OPTS. 


On Windows : 

Update build.bat with following command
set MAVEN_OPTS=-Xmx512m


On Linux :

Update build.sh with following command
export MAVEN_OPTS=-Xmx512m

Tuesday, March 20, 2012

JSP Interview Questions 2

How does JSP handle run-time exceptions?

You can use the errorPage attribute of the page directive to have uncaught run-time exceptions automatically forwarded to an error processing page. For example:
<%@ page errorPage=\"error.jsp\" %> redirects the browser to the JSP page error.jsp if an uncaught exception is encountered during request processing. Within error.jsp, if you indicate that it is an error-processing page, via the directive: <%@ page isErrorPage=\"true\" %> Throwable object describing the exception may be accessed within the error page via the exception implicit object. Note: You must always use a relative URL as the value for the errorPage attribute.

What are the implicit objects?

Implicit objects are objects that are created by the web container and contain information related to a particular request, page, or application. They are: request, response, pageContext, session, application, out, config, page, exception.


Why are JSP pages the preferred API for creating a web-based client program?

Because no plug-ins or security policy files are needed on the client systems(applet does). Also, JSP pages enable cleaner and more module application design because they provide a way to separate applications programming from web page design. This means personnel involved in web page design do not need to understand Java programming language syntax to do their jobs.



Is JSP technology extensible?


Yes. JSP technology is extensible through the development of custom actions, or tags, which are encapsulated in tag libraries.


What is the page directive is used to prevent a JSP page from automatically creating a session?

<%@ page session="false">

What is the difference between RequestDispatcher and sendRedirect?

RequestDispatcher: server-side redirect with request and response objects. sendRedirect : Client-side redirect with new request and response objects.

JSP Interview Questions 1

Explain the life-cycle mehtods in JSP?

THe generated servlet class for a JSP page implements the HttpJspPage interface of the javax.servlet.jsp package. Hte HttpJspPage interface extends the JspPage interface which inturn extends the Servlet interface of the javax.servlet package. the generated servlet class thus implements all the methods of the these three interfaces. The JspPage interface declares only two mehtods - jspInit() and jspDestroy() that must be implemented by all JSP pages regardless of the client-server protocol. However the JSP specification has provided the HttpJspPage interfaec specifically for the JSp pages serving HTTP requests. This interface declares one method _jspService().
The jspInit()- The container calls the jspInit() to initialize te servlet instance.It is called before any other method, and is called only once for a servlet instance.
The _jspservice()- The container calls the _jspservice() for each request, passing it the request and the response objects.
The jspDestroy()- The container calls this when it decides take the instance out of service. It is the last method called n the servlet instance.


Difference between forward and sendRedirect?

When you invoke a forward request, the request is sent to another resource on the server, without the client being informed that a different resource is going to process the request. This process occurs completly with in the web container. When a sendRedirtect method is invoked, it causes the web container to return to the browser indicating that a new URL should be requested. Because the browser issues a completly new request any object that are stored as request attributes before the redirect occurs will be lost. This extra round trip a redirect is slower than forward.

What are implicit objects? List them?

Certain objects that are available for the use in JSP documents without being declared first. These objects are parsed by the JSP engine and inserted into the generated servlet. The implicit objects re listed below
    * request
    * response
    * pageContext
    * session
    * application
    * out
    * config
    * page
    * exception

What is a Declaration?
A declaration declares one or more variables or methods for use later in the JSP source file.

A declaration must contain at least one complete declarative statement. You can declare any number of variables or methods within one declaration tag, as long as they are separated by semicolons. The declaration must be valid in the scripting language used in the JSP file.

<%! somedeclarations %>
<%! int i = 0; %>
<%! int a, b, c; %>

 What is a Expression?

An expression tag 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 text in a JSP file. Like
<%= someexpression %>
<%= (new java.util.Date()).toLocaleString() %>
You cannot use a semicolon to end an expression


What is a Scriptlet?

A scriptlet can contain any number of language statements, variable or method declarations, or expressions that are valid in the page scripting language.Within scriptlet tags, you can

1.Declare variables or methods to use later in the file (see also Declaration).

2.Write expressions valid in the page scripting language (see also Expression).

3.Use any of the JSP implicit objects or any object declared with a tag.
You must write plain text, HTML-encoded text, or other JSP tags outside the scriptlet.

Scriptlets are executed at request time, when the JSP engine processes the client request. If the scriptlet produces output, the output is stored in the out object, from which you can display it.










What are the different scope valiues for the ?

The different scope values for are
1. page
2. request
3.session
4.application



What is a output comment?
A comment that is sent to the client in the viewable page source.The JSP engine handles an output comment as uninterpreted HTML text, returning the comment in the HTML output sent to the client. You can see the comment by viewing the page source from your Web browser.

JSP Syntax


Example 1


Displays in the page source:



What is a Hidden Comment?
A comments that documents the JSP page but is not sent to the client. The JSP engine ignores a hidden comment, and does not process any code within hidden comment tags. A hidden comment is not sent to the client, either in the displayed JSP page or the HTML page source. The hidden comment is useful when you want to hide or "comment out" part of your JSP page.

You can use any characters in the body of the comment except the closing --%> combination. If you need to use --%> in your comment, you can escape it by typing --%\>.
JSP Syntax
<%-- comment --%>

Examples
<%@ page language="java" %>

A Hidden Comment

<%-- This comment will not be visible to the colent in the page source --%>


 

Sunday, March 4, 2012

Servlet Interview Question

 What is a Servlet?

Java Servlets are server side components that provides a powerful mechanism for developing server side of web application. Earlier CGI was used to provide server side capabilities for web applications. Although CGI played a major role in the explosion of the Internet, its performance, scalability and reusability issues made it less and less desirable among people who wanted enterprise class scalable applications. Java Servlets was the solution to all of CGIs problems. Built from ground up using Sun's java technology, servlets provide excellent framework for server side processing. They are an integral part of almost all J2EE applications

  What are the types of Servlet?

There are two types of servlets, GenericServlet and HttpServlet. GenericServlet defines the generic or protocol independent servlet. HttpServlet is subclass of GenericServlet and provides http protocl specific functionality.

What are the differences between HttpServlet and Generic Servlets?

GenericServlet defines a generic, protocol-independent servlet whereas HttpServlet Provides an abstract class to be subclassed to create an HTTP servlet suitable for a Web site that uses the Http Protocol.

What are the differences between a Servlet and an Applet?
  •  Servlets are server side components that executes on the server whereas applets are client side components and executes on the web browser.
  •   Applets have GUI interface but there is no GUI interface in case of Servlets.
  •   Applets have limited capabilities whereas Servlets are very poweful and can support a wide variety of operations
  •   Servlets can perform operations like interacting with other servlets, JSP Pages, connect to databases etc while Applets cannot do all this.

  What are the differences between the doGet and doPost methods?
  •   Get sends information from the browser to the Servlet as contents appended to the query string in the URL while Post uses hidden variables
  •   Because of the above point, post is a lot safer than get
  •   Get has a size limitation - i.e., we can send only approximately 1 Kb of data while Post can send a singnificantly higher amount of data
  •   Get is the most common type of sending data from a browser to a servlet, while Post is gaining popularity because of its size and safety which is better than the get.

  What are the different methods present in a HttpServlet?

The methods of HttpServlet class are :

* doGet() - To handle the GET, conditional GET, and HEAD requests
* doPost() - To handle POST requests
* doPut() - To handle PUT requests
* doDelete() - To handle DELETE requests
* doOptions() - To handle the OPTIONS requests and
* doTrace() - To handle the TRACE requests

Apart from these, a Servlet also contains init() and destroy() methods that are used to initialize and destroy the servlet respectively. They are not any operation specific and are available in all Servlets for use during their active life-cycle.


  What are the advantages of Servlets over CGI programs?

Java Servlets have a number of advantages over CGI and other API's. Some are:

1. Platform Independence - Java Servlets are 100% pure Java, so it is platform independent. It can run on any Servlet enabled web server. For example if you develop an web application in windows machine running Java web server. You can easily run the same on apache web server without modification code. Platform independency of servlets provide a great advantages over alternatives of servlets.

2. Performance - Anyone who has used CGI would agree that Servlets are much more powerful and quicker than CGI. Because the underlying technology is Java, it is fast and can handle multiple request simultaneously. Also, a servlet gets initialized only once in its lifetime and then continues to serve requests without having to be re-initialized again, hence the performance is much higher than CGIs.

3. Extensibility - Java Servlets are developed in java which is robust, well-designed and object oriented language which can be extended or polymorphed into new objects. So the java servlets takes all these advantages and can be extended from existing class the provide the ideal solutions.

Also, in terms of Safety & Security Servlets are superior when compared to CGI.

  What are the lifecycle methods of Servlet?

The interface javax.servlet.Servlet, defines the three life-cycle methods. These are:

public void init(ServletConfig config) throws ServletException
public void service( ServletRequest req, ServletResponse res) throws ServletException, IOException
public void destroy()

The container manages the lifecycle of the Servlet. When a new request come to a Servlet, the container performs the following steps:

1. If an instance of the servlet does not exist, the web container
* Loads the servlet class.
* Creates an instance of the servlet class.
* Initializes the servlet instance by calling the init method.
2. The container invokes the service method, passing request and response objects.
3. To remove the servlet, container finalizes the servlet by calling the servlet's destroy method.

What are the type of protocols supported by HttpServlet?

It extends the GenericServlet base class and provides an framework for handling the HTTP protocol. So, HttpServlet only supports HTTP and HTTPS protocol.

  What is ServletContext?

ServletContext is an Interface that defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file. There is one context per "web application" per Java Virtual Machine.

What is meant by Pre-initialization of Servlet?

When servlet container is loaded, all the servlets defined in the web.xml file do not get initialized by default. When the container receives a request to hit a particular servlet, it loads that servlet. But in some cases if you want your servlet to be initialized when context is loaded, you have to use a concept called pre-initialization of Servlet. In this case, the servlet is loaded when context is loaded. You can specify 1 in between the tag in the Web.xml file in order to pre-initialize your servlet

What mechanisms are used by a Servlet Container to maintain session information?

Servlet Container uses Cookies, URL rewriting, and HTTPS protocol information to maintain the session.

What do you understand by servlet mapping?

Servlet mapping defines an association between a URL pattern and a servlet. You can use one servlet to process a number of url patterns. For example in case of Struts *.do url patterns are processed by Struts Controller Servlet.

What interface must be implemented by all Servlets?

The Servlet Interface must be implemented by all servlets (either the GenericServlet or the HttpServlet)

What are the uses of Servlets?
  •   Servlets are used to process the client requests.
  •   A Servlet can handle multiple request concurrently and be used to develop high performance system
  •   A Servlet can be used to load balance among serveral servers, as Servlet can easily forward request.

What are the objects that are received when a servlets accepts call from client?

The objects are:
ServeltRequest and
ServletResponse

The ServeltRequest encapsulates the communication from the client to the
server. While ServletResponse encapsulates the communication from the Servlet back to the client. All the passage of data between the client and server happens by means of these request and response objects.