Difference between ServletConfig and ServletContext

  • Signature: public interface ServletConfig
    ServletConfig is implemented by the servlet container to initialize a single servlet using init(). That is, you can pass initialization parameters to the servlet using the web.xml deployment descriptor. For understanding, this is similar to a constructor in a java class.

Example code:
<servlet>
<servlet-name>ServletConfigTest</servlet-name>
<servlet-class>com.javapapers.ServletConfigTest</servlet-class>
<init-param>
<param-name>topic</param-name>
<param-value>Difference between ServletConfig and ServletContext</param-value>
</init-param>
</servlet>

  • Signature: public interface ServletContext
    ServletContext is implemented by the servlet container for all servlet to communicate with its servlet container, for example, to get the MIME type of a file, to get dispatch requests, or to write to a log file. That is to get detail about its execution environment. It is applicable only within a single Java Virtual Machine. If a web applicationa is distributed between multiple JVM this will not work. For understanding, this is like a application global variable mechanism for a single web application deployed in only one JVM.

The ServletContext object is contained within the ServletConfig object. That is, the ServletContext can be accessed using the ServletConfig object within a servlet. You can specify param-value pairs for ServletContext object in <context-param> tags in web.xml file.

Example code:
<context-param>
<param-name>globalVariable</param-name>
<param-value>javapapers.com</param-value>
</context-param>

Advertisements

Java Server Pages (JSP) Interview Questions

Question 1: Which of the following is not a standard method called as part of the JSP life cycle?

Answer: jspService()

 

Question 2: If you want to override a JSP file’s initialization method, within what type of tags must you declare the method?

Answer: <%! %>

 

Question 3: Which can not be used as the scope when using a JavaBean with JSP?

Answer:  Response is not a valid object scope for JavaBeans

 

Question 4: Why use RequestDispatcher to forward a request to another resource, instead of using a sendRedirect

Answer: The RequestDispatcher does not require a round trip to the client, and thus is more efficient and allows the server to maintain request state.

 

Question 5: What is the key difference between using a <jsp:forward> and HttpServletResponse.sendRedirect()?

Answer: forward executes on the server while sendRedirect() executes on the client.

 

Question 6: How you  makes your compiled JSP page implement the SingleThreadModel interface?

Answer: <%@ page isThreadSafe=”false” %>

 

Question 7: What is the difference between doing an include or a forward with a RequestDispatcher?

 Answer: When the forward method is used, the invoking resource does not regain control. Multiple include invocations can be made from the same resource, while the invoking resource maintains execution control.

 

Question 8: When a JSP page is compiled, what is it turned into?

Answer: Servlet

 

Question 9: What is JavaServer Pages technology?

Answer: JavaServer Pages (JSP) technology provides a simplified, fast way to create web pages that display dynamically generated content. The JSP specification, developed through an industry-wide initiative led by Sun Microsystems, defines the interaction between the server and the JSP page, and describes the format and syntax of the page.

 

Question 10: How does the JavaServer Pages technology work?

Answer: JSP pages use XML tags and scriptlets written in the JavaTM programming language to encapsulate the logic that generates the content for the page. It passes any formatting (HTML or XML) tags directly back to the response page. In this way, JSP pages separate the page logic from its design and display.

 

JSP technology is part of the Java technology family; it uses a Java programming language-based scripting language, and JSP pages are compiled into servlets. JSP pages may call JavaBeansTM components (beans) or Enterprise JavaBeansTM components (enterprise beans) to perform processing on the server. As such, JSP technology is a key component in a highly scalable architecture for web-based applications.

 

JSP pages are not restricted to any specific platform or web server. The JSP specification represents a broad spectrum of industry input.

 

Question 11: Why do I need JSP technology if I already have servlets?

Answer: JSP pages are compiled into servlets, so theoretically you could write servlets to support your web-based applications. However, JSP technology was designed to simplify the process of creating pages by separating web presentation from web content. In many applications, the response sent to the client is a combination of template data and dynamically-generated data. In this situation, it is much easier to work with JSP pages than to do everything with servlets.

 

Question 12: What is a JSP page?

Answer: A JSP page is a page created by the web developer that includes JSP technology-specific tags, declarations, and possibly scriptlets, in combination with other static (HTML or XML) tags. A JSP page has the extension .jsp; this signals to the web server that the JSP engine will process elements on this page.

 

Question 13: How do JSP pages work?

Answer: A JSP engine interprets tags and scriptlets, and generates the content required – for example, by calling a bean, accessing a database with the JDBCTM API or including a file. It then sends the results back in the form of an HTML (or XML) page to the browser. The logic that generates the content is encapsulated in tags and beans processed on the server. JSP scriptlets let developers tie everything together, and ordinary HTML tags control the formatting and display of the generated page.

 

Question 14: How is a JSP page invoked and compiled?

Answer: Pages built using JSP technology are typically implemented using a translation phase that is performed once, the first time the page is called. The page is compiled into a Java Servlet class and remains in server memory, so subsequent calls to the page have very fast response times.

 

Question 15: Can I create XML pages using JSP technology?

Answer: Yes, the JSP specification does support creation of XML documents. For simple XML generation, the XML tags may be included as static template portions of the JSP page. Dynamic generation of XML tags occurs through bean components or custom tags that generate XML output. See the white paper Developing XML Solutions with JavaServer Pages Technology (PDF) for details.

 

Question 16: Can I generate and manipulate JSP pages using XML tools?

Answer: The JSP 1.1 specification describes a mapping between JSP pages and XML documents.The mapping enables the creation and manipulation of JSP pages using XML tools.

 

Question 17: How do I use JavaBeans components (beans) from a JSP page?

Answer: The JSP specification includes standard tags for bean use and manipulation. The useBean tag creates an instance of a specific JavaBeans class. If the instance already exists, it is retrieved. Otherwise, it is created. The setProperty and getProperty tags let you manipulate properties of the given object. These tags are described in more detail in the JSP specification and tutorial.

 

Question 18: Why are there no try/catch blocks around my JSP scriptlets? I know the code should throw errors.

Answer: Don’t be confused. Scriplets do eventually end up with try/catch blocks around thier code. A JSP will catch any thrown error and display it to a user, or optionally handle it with a error page if specified.

 

If you would like to see the error handling examine the generated code by your JSP container.

 

Question 19: How do I call a function in my JSP via client-side JavaScript?

Answer: It is not possible to do that.

 

A common misconception about JSP is where it takes place. JSP occurs only on the server-side. As it implies, client-side JavaScript takes place only on the client’s computer. You cannont interchange the two.

 

Question 20: What are Implicit Objects?

Answer. An implicit object is available for a JSP developer to use inside scriptlets and expressions. The implicit objects represent all of the important components of the PageContext. Implicit objects need not be declared. They already exist and an error will be thrown if another variable of the same name is used.

 

User friendly documentaion of the implicit objects along with code examples is also provided at JSP Insider. Here is a list of the JSP 1.1 implicit objects and links for the documentation provided by JSP Insider.

 

A. pageContext

B. application

C. out

D. response

E. request

F: Session

 

Question 21: Is it possible to pass in any Object other than a String to a taglib?

Answer. Yes, just use an expression. The value of the expression will not be converted to a string in this case.

Take the following example

<example:tag date=”<%= new java.util.Date()%>” />

In the above example, the corresponding tag handler will have the setDate method called with a java.util.Date object passed in as a parameter.

This is perfectly valid in your JSP assuming the tag’s value can be a runtime expression. The TLD for this taglibrary would have to include the following snippet.

<attribute>

<name>date</name>

<rtexprvalue>true</rtexprvalue>

</attribute>

Question 22: Both <%!…%> and <%…%> can be used for declaring variables. What is the difference between both and which to use?

Answer: There is a distinct difference between an declaration, <%!…%>, and a scriptlet, <%…%>.

 

<%!…%> Declares a variable or method valid in the scripting language used in the JSP page.

<%…%> Contains a code fragment valid in the pages scripting language.

 

The big difference is that <%…%> is initialized once per each request to the JSP. Often the <%…%> is prefered and recommended for this reason, variables declared by <%!…%> are only loaded once, at the beginning of the JSP’s lifecycle.

Question 23: What JSP servers are currently available?

Answer: Here’s a list of JSP servers with which we are familiar. This is only a partial list.

Extreme Internet Server

IPlanet WebServer

JRun

Orion

Resin

Tomcat

WebLogic

WebSphere

ServletExec

LiteWebServer

For a more complete list check out the Java server list at the Java Skyline web site. This list contains more than just JSP servers, but it is a great place to start.

Question 24: How do I Pass an Object between a Servlet and a JSP?

Answer: On the server-side you may forward the request with, pageContext.forward(“Relative URI…”); for a JSP, or with getServletConfig().getServletContext().getRequestDispatcher(“Relative URI…”).forward(request, response); for a Servlet. The same HttpServletRequest object is shared when using these methods. Because of this objects may be stashed and retrieved using the getAttribute() and setAttribute() methods of HttpServletRequest.

 

Take for example the following Servlet. A java.lang.String object is set in the request object with “text” as the key. The servlet then fowards to a JSP.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ExampleServlet extends HttpServlet 
{
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException   
  {
   String text  = new String("Some text to pass...");
   request.setAttribute("text", text);
   getServletConfig().getServletContext().getRequestDispatcher("/test.jsp").forward(request, response);

  }
}

 

Using getAttribute(), a JSP can access the object set by the servlet.

 

1
2
3
4
5
6
7
8
9
10
<html>
 <head><title>Passing an object.</title></head>
 <body>
<%
  String text = (String)request.getAttribute("text");
%>
<%= text %>
 </body>
</html>

 

If the result would be a webpage displaying, “Some text to pass…”

 

Any object may be passed using this method. Just remember to use the appropriate type cast when getting the object from the request. This method may also be used to pass objects between only servlets or JSP.

 

Question 25: How can I set a cookie in JSP?

Answer: This should work:

 

response.setHeader(“Set-Cookie”, “cookie string”);

To give the response-object to a bean, write a method setResponse

(HttpServletResponse response)

– to the bean, and in jsp-file:

 

<%

bean.setResponse (response);

%>

 

Question 26: How can I include one JSP inside another JSP?

Answer: <%@ include=”FileName.jsp” %>

Question 27: How do I delete a cookie with JSP?

Answer:

<%

Cookie killCookie = new Cookie(“foo”, null);

killCookie.setPath(“/”);

killCookie.setMaxAge(0);

response.addCookie(killCookie);

%>

 

Question 28: What is a web application?

Answer: A web application is a collection of resources that is mapped to a specific Uniform Resource Identifier (URI) prefix. These resources may include JSP pages, Servlets, HTML files, and images.

 

Question 29: If you want to override a JSP file’s initialization method, within what type of tags must you declare the method?

Answer: <%! %>

 

Question 30: Why use RequestDispatcher to forward a request to another resource, instead of using a sendRedirect?

Answer: The RequestDispatcher does not require a round trip to the client, and thus is more efficient and allows the server to maintain request state.

 

Question 31: What is the key difference between using a <jsp:forward> and HttpServletResponse.sendRedirect()?

Answer: forward executes on the server while sendRedirect() executes on the client.

 

Question 32. What is the difference between doing an include or a forward with a RequestDispatcher?

Answer: When the forward method is used, the invoking resource does not regain control. Multiple include invocations can be made from the same resource, while the invoking resource maintains execution control.

 

Question 33. What are the elements available in JSP?

Answer: There are three types of elements: directive elements, scripting elements, and action elements.

 

Question 34. How do you invoke a JSP page from a servlet?

Answer:

ServletContext context = getServletConfig().getServletContext();

context.getResourceDispatcher(urlpath).forward(request, response);

(Or)

RequestDispatcher rd = request.getRequestDispatcher(urlpath);

rd.forward(request, response);

 

Question 35. Can JSP and Servlet share same Session and Beans?

Answer: Yes

 

Question 36. What are the different scopes available for usebean tag in JSP?

Answer: Page, Request, Session and Application.

 

 

 

 

 

How Garbage Collection works in Java?

I have read many articles on Garbage Collection in Java, some of them are too complex to understand and some of them don’t contain enough information required to understand garbage collection in Java. Then I decided to write my own experience as an article or you call tutorial about How Garbage Collection works in Java or what is Garbage collection in Java in simple word which would be easy to understand and have sufficient information to understand how garbage collection works in Java.

Few important points about garbage collection in java:

1) objects are created on heap in Java  irrespective of there scope e.g. local or member variable. while its worth noting that class variables or static members are created in method area of Java memory space and both heap and method area is shared between different thread.
2) Garbage collection is a mechanism provided by Java Virtual Machine to reclaim heap space from objects which are eligible for Garbage collection.
3) Garbage collection relieves java programmer from memory management which is essential part of C++ programming and gives more time to focus on business logic.
4) Garbage Collection in Java is carried by a daemon thread called Garbage Collector.
5) Before removing an object from memory Garbage collection thread invokes finalize () method of that object and gives an opportunity to perform any sort of cleanup required.
6) You as Java programmer can not force Garbage collection in Java; it will only trigger if JVM thinks it needs a garbage collection based on Java heap size.
7) There are methods like System.gc () and Runtime.gc () which is used to send request of Garbage collection to JVM but it’s not guaranteed that garbage collection will happen.
8) If there is no memory space for creating new object in Heap Java Virtual Machine throws OutOfMemoryError or java.lang.OutOfMemoryError heap space


9) J2SE 5(Java 2 Standard Edition) adds a new feature called Ergonomics goal of ergonomics is to provide good performance from the JVM with minimum of command line tuning.

When an Object becomes Eligible for Garbage Collection

An Object becomes eligible for Garbage collection or GC if its not reachable from any live threads or any static refrences in other words you can say that an object becomes eligible for garbage collection if its all references are null. Cyclic dependencies are not counted as reference so if Object A has reference of object B and object B has reference of Object A and they don’t have any other live reference then both Objects A and B will be eligible for Garbage collection.
Generally an object becomes eligible for garbage collection in Java on following cases:
1) All references of that object explicitly set to null e.g. object = null
2) Object is created inside a block and reference goes out scope once control exit that block.
3) Parent object set to null, if an object holds reference of another object and when you set container object’s reference null, child or contained object automatically becomes eligible for garbage collection.
4) If an object has only live references via WeakHashMap it will be eligible for garbage collection. To learn more about HashMap see here How HashMap works in Java.

Heap Generations for Garbage Collection in Java

Java objects are created in Heap and Heap is divided into three parts or generations for sake of garbage collection in Java, these are called as Young generation, Tenured or Old Generation and Perm Area of heap.
New Generation is further divided into three parts known as Eden space, Survivor 1 and Survivor 2 space. When an object first created in heap its gets created in new generation inside Eden space and after subsequent Minor Garbage collection if object survives its gets moved to survivor 1 and then Survivor 2 before Major Garbage collection moved that object to Old or tenured generation.

Permanent generation of Heap or Perm Area of Heap is somewhat special and it is used to store Meta data related to classes and method in JVM, it also hosts String pool provided by JVM as discussed in my string tutorial why String is immutable in Java. There are many opinions around whether garbage collection in Java happens in perm area of java heap or not, as per my knowledge this is something which is JVM dependent and happens at least in Sun’s implementation of JVM. You can also try this by just creating millions of String and watching for Garbage collection or OutOfMemoryError.

Types of Garbage Collector in Java

Java Runtime (J2SE 5) provides various types of Garbage collection in Java which you can choose based upon your application’s performance requirement. Java 5 adds three additional garbage collectors except serial garbage collector. Each is generational garbage collector which has been implemented to increase throughput of the application or to reduce garbage collection pause times.

1) Throughput Garbage Collector: This garbage collector in Java uses a parallel version of the young generation collector. It is used if the -XX:+UseParallelGC option is passed to the JVM via command line options . The tenured generation collector is same as the serial collector.

2) Concurrent low pause Collector: This Collector is used if the -Xingc or -XX:+UseConcMarkSweepGC is passed on the command line. This is also referred as Concurrent Mark Sweep Garbage collector. The concurrent collector is used to collect the tenured generation and does most of the collection concurrently with the execution of the application. The application is paused for short periods during the collection. A parallel version of the young generation copying collector is sued with the concurrent collector. Concurrent Mark Sweep Garbage collector is most widely used garbage collector in java and it uses algorithm to first mark object which needs to collected when garbage collection triggers.

3) The Incremental (Sometimes called train) low pause collector: This collector is used only if –XX:+UseTrainGC is passed on the command line. This garbage collector has not changed since the java 1.4.2 and is currently not under active development. It will not be supported in future releases so avoid using this and please see 1.4.2 GC Tuning document for information on this collector.
Important point to not is that -XX:+UseParallelGC should not be used with -XX:+UseConcMarkSweepGC. The argument passing in the J2SE platform starting with version 1.4.2 should only allow legal combination of command line options for garbage collector but earlier releases may not find or detect all illegal combination and the results for illegal combination are unpredictable. It’s not recommended to use this garbage collector in java.

JVM Parameters for garbage collection in Java

Garbage collection tuning is a long exercise and requires lot of profiling of application and patience to get it right. While working with High volume low latency Electronic trading system I have worked with some of the project where we need to increase the performance of Java application by profiling and finding what causing full GC and I found that Garbage collection tuning largely depends on application profile, what kind of object application has and what are there average lifetime etc. for example if an application has too many short lived object then making Eden space wide enough or larger will reduces number of minor collections. you can also control size of both young and Tenured generation using JVM parameters for example setting -XX:NewRatio=3 means that the ratio among the young and tenured generation is 1:3 , you got to be careful on sizing these generation. As making young generation larger will reduce size of tenured generation which will force Major collection to occur more frequently which pauses application thread during that duration results in degraded or reduced throughput. The parameters NewSize and MaxNewSize are used to specify the young generation size from below and above. Setting these equal to one another fixes the young generation. In my opinion before doing garbage collection tuning detailed understanding of garbage collection in java is must and I would recommend reading Garbage collection document provided by Sun Microsystems for detail knowledge of garbage collection in Java. Also to get a full list of JVM parameters for a particular Java Virtual machine please refer official documents on garbage collection in Java. I found this link quite helpful though http://www.oracle.com/technetwork/java/gc-tuning-5-138395.html

Full GC and Concurrent Garbage Collection in Java

Concurrent garbage collector in java uses a single garbage collector thread that runs concurrently with the application threads with the goal of completing the collection of the tenured generation before it becomes full. In normal operation, the concurrent garbage collector is able to do most of its work with the application threads still running, so only brief pauses are seen by the application threads. As a fall back, if the concurrent garbage collector is unable to finish before the tenured generation fill up, the application is paused and the collection is completed with all the application threads stopped. Such Collections with the application stopped are referred as full garbage collections or full GC and are a sign that some adjustments need to be made to the concurrent collection parameters. Always try to avoid or minimize full garbage collection or Full GC because it affects performance of Java application. When you work in finance domain for electronic trading platform and with high volume low latency systems performance of java application becomes extremely critical an you definitely like to avoid full GC during trading period.

Summary on Garbage collection in Java

1) Java Heap is divided into three generation for sake of garbage collection. These are young generation, tenured or old generation and Perm area.
2) New objects are created into young generation and subsequently moved to old generation.
3) String pool is created in Perm area of Heap, garbage collection can occur in perm space but depends upon JVM to JVM.
4) Minor garbage collection is used to move object from Eden space to Survivor 1 and Survivor 2 space and Major collection is used to move object from young to tenured generation.
5) Whenever Major garbage collection occurs application threads stops during that period which will reduce application’s performance and throughput.
6) There are few performance improvement has been applied in garbage collection in java 6 and we usually use JRE 1.6.20 for running our application.
7) JVM command line options –Xmx and -Xms is used to setup starting and max size for Java Heap. Ideal ratio of this parameter is either 1:1 or 1:1.5 based upon my experience for example you can have either both –Xmx and –Xms as 1GB or –Xms 1.2 GB and 1.8 GB.
8) There is no manual way of doing garbage collection in Java.

Source : javarevisited

How HashMap works in Java?

How HashMap works in Java or sometime how get method work in HashMap is common interview questions now days. Almost everybody who worked in Java knows what hashMap is, where to use hashMap or difference between hashtable and HashMap then why this interview question becomes so special? Because of the breadth and depth this question offers. It has become very popular java interview question in almost any senior or mid-senior level java interviews.

Questions start with simple statement

“Have you used HashMap before” or “What is HashMap? Why do we use it “
Almost everybody answers this with yes and then interviewee keep talking about common facts about hashMap like hashMap accpt null while hashtable doesn’t, HashMap is not synchronized, hashMap is fast and so on along with basics like its stores key and value pairs etc.
This shows that person has used hashMap and quite familier with the funtionalities HashMap offers but interview takes a sharp turn from here and next set of follow up questions gets more detailed about fundamentals involved in hashmap. Interview here you and come back with questions like

“Do you Know how hashMap works in Java” or
“How does get () method of HashMap works in Java”
And then you get answers like I don’t bother its standard Java API, you better look code on java; I can find it out in Google at any time etc.
But some interviewee definitely answer this and will say “HashMap works on principle of hashing, we have put () and get () method for storing and retrieving data from hashMap. When we pass an object to put () method to store it on hashMap, hashMap implementation calls
hashcode() method hashMap key object and by applying that hashcode on its own hashing funtion it identifies a bucket location for storing value object , important part here is HashMap stores both key+value in bucket which is essential to understand the retrieving logic. if people fails to recognize this and say it only stores Value in the bucket they will fail to explain the retrieving logic of any object stored in HashMap . This answer is very much acceptable and does make sense that interviewee has fair bit of knowledge how hashing works and how HashMap works in Java.
But this is just start of story and going forward when depth increases a little bit and when you put interviewee on scenarios every java developers faced day by day basis. So next question would be more likely about collision detection and collision resolution in Java HashMap e.g

“What will happen if two different objects have same hashcode?”
Now from here confusion starts some time interviewer will say that since Hashcode is equal objects are equal and HashMap will throw exception or not store it again etc. then you might want to remind them aobut equals and hashCode() contract that two unequal object in Java very much can have equal hashcode. Some will give up at this point and some will move ahead and say “Since hashcode () is same, bucket location would be same and collision occurs in hashMap, Since HashMap use a linked list to store in bucket, value object will be stored in next node of linked list.” great this answer make sense to me though there could be some other collision resolution methods available this is simplest and HashMap does follow this.
But story does not end here and final questions interviewer ask like

“How will you retreive if two different objects have same hashcode?”
Hmmmmmmmmmmmmm
Interviewee will say we will call get() method and then HashMap uses keys hashcode to find out bucket location and retreives object but then you need to remind him that there are two objects are stored in same bucket , so they will say about traversal in linked list until we find the value object , then you ask how do you identify vlaue object because you don’t value object to compare ,So until they know that HashMap stores both Key and Value in linked list node they won’t be able to resolve this issue and will try and fail.

But those bunch of people who remember this key information will say that after finding bucket location , we will call keys.equals() method to identify correct node in linked list and return associated value object for that key in Java HashMap. Perfect this is the correct answer.

In many cases interviewee fails at this stage because they get confused between hashcode () and equals () and keys and values object in hashMap which is pretty obvious because they are dealing with the hashcode () in all previous questions and equals () come in picture only in case of retrieving value object from HashMap.
Some good developer point out here that using immutable, final object with proper equals () and hashcode () implementation would act as perfect Java HashMap keys and improve performance of Java hashMap by reducing collision. Immutablity also allows caching there hashcode of different keys which makes overall retreival process very fast and suggest that String and various wrapper classes e.g Integer provided by Java Collection API are very good HashMap keys.

Now if you clear all this java hashmap interview question you will be surprised by this very interesting question “What happens On HashMap in Java if the size of the Hashmap exceeds a given threshold defined by load factor ?”. Until you know how hashmap works exactly you won’t be able to answer this question.
if the size of the map exceeds a given threshold defined by load-factor e.g. if load factor is .75 it will act to re-size the map once it filled 75%. Java Hashmap does that by creating another new bucket array of size twice of previous size of hashmap, and then start putting every old element into that new bucket array and this process is called rehashing because it also applies hash function to find new bucket location.

If you manage to answer this question on hashmap in java you will be greeted by “do you see any problem with resizing of hashmap in Java” , you might not be able to pick the context and then he will try to give you hint about multiple thread accessing the java hashmap and potentially looking for race condition on HashMap in Java.

So the answer is Yes there is potential race condition exists while resizing hashmap in Java, if two thread at the same time found that now Java Hashmap needs resizing and they both try to resizing. on the process of resizing of hashmap in Java , the element in bucket which is stored in linked list get reversed in order during there migration to new bucket because java hashmap doesn’t append the new element at tail instead it append new element at head to avoid tail traversing. if race condition happens then you will end up with an infinite loop. though this point you can potentially argue that what the hell makes you think to use HashMap in multi-threaded environment to interviewer 🙂

I like this question because of its depth and number of concept it touches indirectly, if you look at questions asked during interview this HashMap questions has verified
Concept of hashing
Collision resolution in HashMap
Use of equals () and hashCode () method and there importance?
Benefit of immutable object?
race condition on hashmap in Java
Resizing of Java HashMap

Just to summararize here are the answers which does makes sense for above questions

How HashMAp works in Java
HashMap works on principle of hashing, we have put () and get () method for storing and retrieving object form hashMap.When we pass an both key and value to put() method to store on HashMap, it uses key object hashcode() method to calculate hashcode and they by applying hashing on that hashcode it identifies bucket location for storing value object.
While retrieving it uses key object equals method to find out correct key value pair and return value object associated with that key. HashMap uses linked list in case of collision and object will be stored in next node of linked list.
Also hashMap stores both key+value tuple in every node of linked list.

What will happen if two different HashMap key objects have same hashcode?
They will be stored in same bucket but no next node of linked list. And keys equals () method will be used to identify correct key value pair in HashMap.

In terms of usage HashMap is very versatile and I have mostly used hashMap as cache in electronic trading application I have worked . Since finance domain used Java heavily and due to performance reason we need caching a lot HashMap comes as very handy there.

Source : javarevisited

How Synchronization works in Java ? Example of synchronized block

In this Java synchronization tutorial we will see what is meaning of Synchronization in Java, Why do we need Synchronization in java, what is java synchronized keyword, example of using java synchronized method and blocks and important points about synchronization in Java.

Example of Synchronization in Java using synchronized method and block

Synchronization in Java is an important concept since Java is a multi-threaded language where multiple threads run in parallel to complete program execution. In multi-threaded environment synchronization of java object or synchronization of java class becomes extremely important. Synchronization in Java is possible by using java keyword “synchronized” and “volatile”. Concurrent access of shared objects in Java introduces to kind of errors: thread interference and memory consistency errors and to avoid these errors you need to properly synchronize your java object to allow mutual exclusive access of critical section to two threads.

This Java Synchronization tutorial is in continuation of my article How HashMap works in Java  and difference between HashMap and Hashtable in Java  if you haven’t read already you may find some useful information based on my experience in Java Collections.

Why do we need Synchronization in Java?

If your code is executing in multi-threaded environment you need synchronization for objects which are shared among multiple threads to avoid any corruption of state or any kind of unexpected behavior. Synchronization in Java will only be needed if shared object is mutable. if your shared object is read only or immutable object you don’t need synchronization despite running multiple threads. Same is true with what threads are doing with object if all the threads are only reading value then you don’t require synchronization in java. JVM guarantees that Java synchronized code will only be executed by one thread at a time.In Summary Java Synchronized Keyword provides following functionality essential for concurrent programming :

1) synchronized keyword in java provides locking which ensures mutual exclusive access of shared resource and prevent data race.

2) synchronized keyword also prevent reordering of code statement by compiler which can cause subtle concurrent issue if we don’t use synchronized or volatile keyword.
3) synchronized keyword involve locking and unlocking. before entering into synchronized method or block thread needs to acquire the lock at this point it reads data from main memory than cache and when it release the lock it flushes write operation into main memory which eliminates memory inconsistency errors.

Synchronized keyword in Java

Prior to Java5 synchronized keyword in java was only way to provide synchronization of shared object. Any code written in synchronized block in java will be mutual exclusive and can only be executed by one thread at a time. You can have both static synchronized method and non static synchronized method and synchronized blocks in java but we can not have synchronized variable in java. Using synchronized keyword with variable is illegal and will result in compilation error. Instead of java synchronized variable you can have java volatile variable, which will instruct JVM threads to read value of volatile variable from main memory and don’t cache it locally. Block synchronization in java is preferred over method synchronization in java because by using block synchronization you only need to lock the critical section of code instead of whole method. Since java synchronization comes with cost of performance we need to synchronize only part of code which absolutely needs to be synchronized.

Example of synchronized method in Java

Using synchronized keyword along with method is easy just apply synchronized keyword in front of method. What we need to take care is that static synchronized method locked on class object lock and non static synchronized method locks on current object (this). So it’s possible that both static and non static java synchronized method running in parallel.  This is the common mistake a naive developer do while writing java synchronized code.
public class Counter{
private static count = 0;
public static synchronized  getCount(){
  return this.count;
}
public synchoronized setCount(int count){
   this.count = count;
}
}
In this example of java synchronization code is not properly synchronized because both getCount() and setCount() are not getting locked on same object and can run in parallel which results in getting incorrect count. Here getCount() will lock in Counter.class object while setCount() will lock on current object (this). To make this code properly synchronized in java you need to either make both method static or non static or use java synchronized block instead of java synchronized method.

Example of synchronized block in Java

Using synchronized block in java is also similar to using synchronized keyword in methods. Only important thing to note here is that if object used to lock synchronized block of code, Singleton.class in below example is null then java synchronized block will throw a NullPointerException.
public class Singleton{
private static volatile Singleton _instance;
public static Singleton getInstance(){
   if(_instance == null){
            synchronized(Singleton.class){
              if(_instance == null)
              _instance = new Singleton();
            }
   }
   return _instance;
}
This is a classic example of double checked locking in Singleton. In this example of java synchronized code we have made only critical section (part of code which is creating instance of singleton) synchronized and saved some performance because if you make whole method synchronized every call of this method will be blocked while you only need to create instance on first call. To read more about Singleton in Java see here.

Important points of synchronized keyword in Java

1. Synchronized keyword in Javais used to provide mutual exclusive access of a shared resource with multiple threads in Java. Synchronization in java guarantees that no two threads can execute a synchronized method which requires same lock simultaneously or concurrently.

2. You can use java synchronized keyword only on synchronized method or synchronized block.
3. When ever a thread enters into java synchronized method or block it acquires a lock and whenever it leaves java synchronized method or block it releases the lock. Lock is released even if thread leaves synchronized method after completion or due to any Error or Exception.
4. Java Thread acquires an object level lock when it enters into an instance synchronized java method and acquires a class level lock when it enters into static synchronized java method.
5.java synchronized keyword is re-entrant in nature it means if a java synchronized method calls another synchronized method which requires same lock then current thread which is holding lock can enter into that method without acquiring lock.
6. Java Synchronization will throw NullPointerException if object used in java synchronized block is null e.g. synchronized (myInstance) will throws NullPointerException if myInstance is null.
7. One Major disadvantage of java synchronized keyword is that it doesn’t allow concurrent read which you can implement using java.util.concurrent.locks.ReentrantLock.
8. One limitation of java synchronized keyword is that it can only be used to control access of shared object within the same JVM. If you have more than one JVM and need to synchronized access to a shared file system or database, the java synchronized keyword is not at all sufficient. You need to implement a kind of global lock for that.
9. Java synchronized keyword incurs performance cost. Synchronized method in Java is very slow and can degrade performance. So use synchronization in java when it absolutely requires and consider using java synchronized block for synchronizing critical section only.
10. Java synchronized block is better than java synchronized method in java because by using synchronized block you can only lock critical section of code and avoid locking whole method which can possibly degrade performance. A good example of java synchronization around this concept is getInstance() method Singleton class. See here.
11. Its possible that both static synchronized and non static synchronized method can run simultaneously or concurrently because they lock on different object.
12. From java 5 after change in Java memory model reads and writes are atomic for all variables declared using volatile keyword (including long and double variables) and simple atomic variable access is more efficient instead of accessing these variables via synchronized java code. But it requires more care and attention from the programmer to avoid memory consistency errors.
13. Java synchronized code could result in deadlock or starvation while accessing by multiple thread if synchronization is not implemented correctly. To know how to avoid deadlock in java see here.
14. According to the Java language specification you can not use java synchronized keyword with constructor it’s illegal and result in compilation error. So you can not synchronized constructor in Java which seems logical because other threads cannot see the object being created until the thread creating it has finished it.
15. You cannot apply java synchronized keyword with variables and can not use java volatile keyword with method.
16. Java.util.concurrent.locks extends capability provided by java synchronized keyword for writing more sophisticated programs since they offer more capabilities e.g. Reentrancy and interruptible locks.
17. java synchronized keyword also synchronizes memory. In fact java synchronized synchronizes the whole of thread memory with main memory.

18. Important method related to synchronization in Java are wait(), notify() and notifyAll() which is defined in Object class.

19. Do not synchronize on non final field on synchronized block in Java. because reference of non final field may change any time and then different thread might synchronizing on different objects i.e. no synchronization at all. example of synchronizing on non final field :

private String lock = new String(“lock”);
synchronized(lock){
System.out.println(“locking on :”  + lock);

}
any if you write synchronized code like above in java you may get warning “Synchronization on non-final field”  in IDE like Netbeans and InteliJ

20. Its not recommended to use String object as lock in java synchronized block because string is immutable object and literal string and interned string gets stored in String pool. so by any chance if any other part of code or any third party library used same String as there lock then they both will be locked on same object despite being completely unrelated which could result in unexpected behavior and bad performance. instead of String object its advised to use new Object() for Synchronization in Java on synchronized block.

private static final String LOCK = “lock”;   //not recommended
private static final Object OBJ_LOCK = new Object(); //better

public void process() {
synchronized(LOCK) {
……..
}
}

21. From Java library Calendar and SimpleDateFormat classes are not thread-safe and requires external synchronization in Java to be used in multi-threaded environment.

Source : javarevisited

Java Serialization Interview questions

Java Serialization is one of important concept but it’s been rarely used as persistence solution and developer mostly overlooked java serialization API.  As per my experience Java Serialization is quite an important topic in any java interview, In almost all the interview I have faced there is one or two java serialization questions and I have seen interview where after few question on serialization candidate start feeling uncomfortable because of lack of experience in this area. They don’t know how to serialize object in java or they are not familiar with any java serialization example to explain.

Most commercial project uses either database or memory mapped file or simply flat file for there persistence requirement and only few of them rely on java serialization. Anyway this post is not a java serialization tutorial or how to serialize in java but about few interview questions around java serialization which is worth to have a look before going for any java interview and surprising yourself with some unknown contents. for those who are not familiar about java Serialization  “Java serialization is the process which is used to serialize object in java by storing object’s state into a file with extension .ser and recreating object’s state from that file, this reverse process is called deserialization.
The Java Serialization API provides a standard mechanism for developers to handle object serialization using Serializable and Externalizable interface.
1) What is the difference between Serializable and Externalizable interface in Java?
This is most frequently asked question in java serialization interview. Here is my version Externalizable provides us writeExternal () and readExternal () method which gives us flexibility to control java serialization mechanism instead of relying on java’s default serialization. Correct implementation of Externalizable interface can improve performance of application drastically.
2) How many methods Serializable has? If no method then what is the purpose of Serializable interface?
Serializable interface exists in java.io  package and forms core of java serialization mechanism. It doesn’t have any method and also called Marker Interface. When your class implements Serializable interface it becomes Serializable in Java and gives compiler an indication that use Java Serialization mechanism to serialize this object.
3) What is serialVersionUID? What would happen if you don’t define this?
SerialVersionUID is an ID which is stamped on object when it get serialized usually hashcode of object, you can use tool serialver to see serialVersionUID of a serialized object . serialVersionUID is used for version control of object. you can specify serialVersionUID in your class file also.  Consequence of not specifying  serialVersionUID is that when you add or modify any field in class then already serialized class will not be able to recover because serialVersionUID generated for new class and for old serialized object will be different. Java serialization process relies on correct serialVersionUID for recovering state of serialized object and throws java.io.InvalidClassException in case of serialVersionUID mismatch.
4) While serializing you want some of the members not to serialize? How do you achieve it?
this is sometime also asked as what is the use of transient variable, does transient and static variable gets serialized or not etc. so if you don’t want any field to be part of object’s state then declare it either static or transient based on your need and it will not be included during java serialization process.
5) What will happen if one of the members in the class doesn’t implement Serializable interface?
If you try to serialize an object of a class which implements Serializable, but the object includes a reference to an non- Serializable class then a ‘NotSerializableException’ will be thrown at runtime and this is why I always put a SerializableAlert (comment section in my code) to instruct developer to remember this fact while adding a new field in a Serializable class.
6) If a class is Serializable but its super class in not, what will be the state of the instance variables inherited from super class after deserialization?
Java serialization process  only continues in object hierarchy till the class is Serializable i.e. implements Serializable interface in Java And values of the instance variables inherited from super class will be initialized by calling constructor of Non-Serializable Super class during deserialization process . once the constructor chaining will started it wouldn’t be possible to stop that , hence even if classes higher in hierarchy implements Serializable interface , there constructor will be executed.
7) Can you Customize Serialization process or can you override default Serialization process in Java?
The answer is yes you can. We all know that for serializing an object objectOutputStream.writeObject (saveThisobject) is invoked and for reading object ObjectInputStream.readObject () is invoked but there is one more thing which Java Virtual Machine provides you is to define these two method in your class. If you define these two methods in your class then JVM will invoke these two methods instead of applying default serialization mechanism. You can customize behavior of object serialization or deserialization here by doing any kind of pre or post processing task. Important point to note is making these methods private to avoid being inherited, overridden or overloaded. Since only Java Virtual Machine can call private method integrity of your class will remain and Java Serialization will work as normal.
8) Suppose super class of a new class implement Serializable interface, how can you avoid new class to being serialized?
If Super Class of a Class already implements Serializable interface in Java then its already serializable in Java, since you can not unimplemented an interface its not really possible to make it Non Serializable class but yes there is a way to avoid serialization of new class. To avoid java serialization you need to implement writeObject () and readObject () method in your Class and need to throw NotSerializableException from those method. This is another benefit of customizing java serialization process as described in above question and normally it asked as follow-up question as interview progresses.
9) Which methods are used during Serialization and DeSerialization process in java?
This is quite a common question basically interviewer is trying to know that whether you are familiar with usage of readObject (), writeObject (), readExternal () and writeExternal () or not. Java Serialization is done by java.io.ObjectOutputStream class. That class is a filter stream which is wrapped around a lower-level byte stream to handle the serialization mechanism. To store any object via serialization mechanism we call objectOutputStream.writeObject (saveThisobject) and to deserialize that object we call ObjectInputStream.readObject () method. Call to writeObject () method trigger serialization process in java. one important thing to note about readObject() method is that it is used to read bytes from the persistence and to create object from those bytes and its return an Object which needs to be casted on correct type.
10) Suppose you have a class which you serialized it and stored in persistence and later modified that class to add a new field. What will happen if you deserialize the object already serialized?
It depends on whether class has its own serialVersionUID or not. As we know from above question that if we don’t provide serialVersionUID in our code java compiler will generate it and normally it’s equal to hash code of object. by adding any new field there is chance that new serialVersionUID generated for that class version is not the same of already serialized object and in this case Java Serialization API will throw java.io.InvalidClassException and this is the reason its recommended to have your own serialVersionUID in code and make sure to keep it same always for a single class.
11) What are the compatible changes and incompatible changes in Java Serialization Mechanism?
The real challenge lies with change in class structure by adding any field, method or removing any field or method is that with already serialized object. As per Java Serialization specification adding any field or method comes under compatible change and changing class hierarchy or unimplementing Serializable interfaces some under non compatible changes. For complete list of compatible and non compatible changes I would advise reading java serialization specification.
12) Can we transfer a Serialized object vie network?
Yes you can transfer a Serialized object via network because java serialized object remains in form of bytes which can be transmitter via network.
13) Which kind of variables is not serialized during Java Serialization?
This question asked sometime differently but the purpose is same whether Java developer knows specifics about static and transient variable or not. Since static variables belong to the class and not to an object they are not the part of the state of object so they are not saved during Java Serialization process. As Java Serialization only persist state of object and not object itself. Transient variables are also not included in java serialization process and are not the part of the object’s serialized state. After this question sometime interviewer ask a follow-up if you don’t store values of these variables then what would be value of these variable once you deserialize and recreate those object? This is for you guys to think about 🙂
Source : javarevisited

Difference between HashMap and HashTable? Can we make hashmap synchronized? HashTable vs HashMap?

This question often asked in interview to check whether candidate understand correct usage of collection classes and aware of alternative solutions available.

  •  The HashMap class is roughly equivalent to Hashtable, except that it is non synchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesn’t allow nulls).
  • HashMap does not guarantee that the order of the map will remain constant over time.
  • HashMap is non synchronized whereas Hashtable is synchronized.
  • Iterator in the HashMap is  fail-fast  while the enumerator for the Hashtable is not and throw ConcurrentModificationException if any other Thread modifies the map structurally  by adding or removing any element except Iterator’s own remove()  method. But this is not a guaranteed behavior and will be done by JVM on best effort.
Note on Some Important Terms
  1. Synchronized means only one thread can modify a hash table at one point of time. Basically, it means that any thread before performing an update on a hashtable will have to acquire a lock on the object while others will wait for lock to be released.
  2. Fail-safe is relevant from the context of iterators. If an iterator has been created on a collection object and some other thread tries to modify the collection object “structurally”, a concurrent modification exception wjavascript:void(0)ill be thrown. It is possible for other threads though to invoke “set” method since it doesn’t modify the collection “structurally”. However, if prior to calling “set”, the collection has been modified structurally, “IllegalArgumentException” will be thrown.
  3. Structurally modification means deleting or inserting element which could effectively change the structure of map.
    HashMap can be synchronized by
    Map m = Collections.synchronizeMap(hashMap);
Some more differences between hashtable and hashmap
  1. hashtable extends Dictionary interface which is quite old while hashmap extends Map interface.
  2. hashtalbe doesn’t have counterpart like ConcurrentHashMap.
  3. another important difference between hashtable and hashmap is , hashtable is less secure than hashmap because of Enumeration it uses. while hashmap uses iterator which prevents Concurrent Modification of HashMap, which is not possible in case of hashtable.
  4. stay out of hashtable use hashmap instead.

 

Hope this will be useful.