Wednesday, June 15, 2011

What is deadlock in Java ? How to fix it ?

What is deadlock in Java ? How to fix it ?

This is one of the question which is flavor of the season for multithreading , asked more at a senior level and with lots of follow up questions , though question looks very basic but most of developer get stuck once you start going deep.

questions starts with "What is deadlock ?"
answer is simple , when two or more threads waiting for each other to release lock and get stuck for infinite time , situation is called deadlock . it will only happen in case of multithreading.

How do you detect deadlock ?
though this could have many answers , my version is first I would look the code if I see nested synchronized block or calling one synchronized method from other or trying to get lock on different object then there is good chance of deadlock if developer is not very careful.

other way is to find it when you actually get locked while running the application , try to take thread dump , in linux you can do this by command "kill -3" , this will print status of all the thread in application log file and you can see which thread is locked on which object.

other way is to use jconsole , jconsole will show you exactly which threads are get locked and on which object.

once you answer this , they may ask you to write code which will result in deadlock ?
here is one of my version

public void method1(){
synchronized(String.class){
System.out.println("Aquired lock on String.class object");

synchronized (Integer.class) {
System.out.println("Aquired lock on Integer.class object");
}
}
}

public void method2(){
synchronized(Integer.class){
System.out.println("Aquired lock on Integer.class object");

synchronized (String.class) {
System.out.println("Aquired lock on String.class object");
}
}
}


If method1() and method2() both will be called by two or many threads , there is a good chance of deadlock becuase if thead 1 aquires lock on Sting object while executing method1() and thread 2 aquires lock on Integer object while executing method2() both will be waiting for each other to release lock on Integer and String to proceed further which will never happen.

now interviewer comes to final part , one of the most important in my view , How to fix deadlock ?

if you have looked above code carefully you may have figured out that real reason for deadlock is not multiple threads but the way they access lock , if you provide an ordered access then problem will be resolved , here is
the fixed version.

public void method1(){
synchronized(Integer.class){
System.out.println("Aquired lock on Integer.class object");

synchronized (String.class) {
System.out.println("Aquired lock on String.class object");
}
}
}

public void method2(){
synchronized(Integer.class){
System.out.println("Aquired lock on Integer.class object");

synchronized (String.class) {
System.out.println("Aquired lock on String.class object");
}
}
}

Now there would not be any deadlock because both method is accessing lock on Integer and String object in same order . so if thead A aquires lock on Integer object , thread B will not proceed until thread A releases Integer lock , same way thread A will not be blocked even if thread B holds String lock because now thread B will not expect thread A to release Integer lock to proceed further.

hope this would be useful.

Thursday, May 12, 2011

What are the differences between SAX and DOM parser.


SAX DOM
Both SAX and DOM are used to parse the XML document. Both has advantages and disadvantages and can be used in our programming depending on the situation.
Parses node by node Stores the entire XML document into memory before processing
Doesn’t store the XML in memory Occupies more memory
We cant insert or delete a node We can insert or delete nodes
Top to bottom traversing Traverse in any direction.
SAX is an event based parser DOM is a tree model parser
SAX is a Simple API for XML Document Object Model (DOM) API
import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
 
doesn’t preserve comments preserves comments
SAX generally runs a little faster than DOM SAX generally runs a little faster than DOM
If we need to find a node and doesn’t need to insert or delete we can go with SAX itself otherwise DOM provided we have more memory.

Interview Question


JSP Interview Question


1.      After hitting submit button, a JSP page processes a database transaction. You have accidentally closed the browser window. Will the database transaction continue or will get over?
2.      What is the difference between http GET and POST methods ?
3.      There are 10 servlets in your web application, and they are frequently used (sticky Servlet). How will you optimize their loading?
4.      How will you communicate across Servlets? (or, how will you achieve Inter Servlet communication?)
5.      Hope, you know the difference between RequestDispatcher.forward() and RequestDispatcher.sendRedirect(). So, which one is desirable to use?
6.      What is the class path hierarchy for a Servlet?
7.      You can’t read files (located out of tomcat directory) from JSP and Servlets for security purpose. But, how will you access those files from JSP or Servlets, in case if you need them?
Answers:
The database transaction will still continue; Because a Servlet thread was created when you hit the JSP page and that runs the database transaction. Closing the browser window will not kill the Servlet thread.
a) GET method passes the form fields as part of URL, but POST method wraps or encrypts the form fields in request data; b) Also, you can pass only 255 characters to the action page with GET method.
Add <load-on-startup> tag to the Servlet in web.xml. This will load your Servlet on startup, and doXXX() method will be ready for any further requests.
Use RequestDispatcher.forward() and RequestDispatcher.include();
RequestDispatcher.sendRedirect() is desirable. Because, forward() can’t work across different JVM.
First, lookup in WEB-INF/classes, then WEB-INF/lib then from tomcat’s central library folder (<tomcat-home>/lib)
Any class from WEB-INF/classes or WEB-INF/lib can access files. So, use those classes to do the job for your JSP and Servlets.

Design Pattern:

1.      How will you design your Singleton Patten class to be thread-safe? (a standard interview question!)
2.      What Design Pattern can be used for classical Producer Consumer problem? (a simple question)
3.      M.S Word can store million lines of text. Each character in the text will have set of properties like font-color, font-size, font-style and etc. So, M.S Word application has to maintain a property structure for each and every character and that may lead to heavy storage. What design pattern will you apply to overcome this problem?
4.      Your application uses 1000 classes and they have interaction among each other. This will lead to complex communication across objects, so what design pattern can solve this problem?
5.      An application reads input from various clients in multiple stages and creates a binary tree structure out of all received inputs. Which design pattern can be used to design such application?
6.      You have to design a budget management application for global users. But, have to provide an option to configure their native tax rules. Which design pattern, do you think, can solve this?
7.      You have a core application class. But, you have to be able assign extra functionalities to the core class on the fly (at runtime). Which patterns deserves this purpose?

1. ANSWER: Adding synchronized keyword tothe getSingleton() method is inefficient solution. Initialize the static private Singleton object within Synchronized block. In this way you can achieve it.
2.ANSWER: Use observer pattern (publisher subscriber model)
3. ANSWER: You have to create property group for each possible styles (font-size, font-color, font-face & etc). So, common characters will be part of a property group, there by reducing the storage of each character. This is called FlyWeight Pattern.
4. ANSWER: Use Mediator pattern to separate the direct communication across objects.
5. ANSWER: Building an object in multiple set - you call it Builder pattern! The realworld example is XSDBuilder class in Java.
6. ANSWER: Use Template Pattern. It provides templates of methods and allowing you to override certain portion of logic.
7. ANSWER: Decorator Pattern. This is similar to the pattern designed for java.io.* classes(BufferedReader, DataInputStream and etc.)

Association, Aggregation, Composition, Abstraction, Generalization, Realization, Dependency
26/06/2010
These terms signify the relationships between classes. These are the building blocks of object oriented programming and very basic stuff. But still for some, these terms look like Latin and Greek. Just wanted to refresh these terms and explain in simpler terms.
Association
Association is a relationship between two objects. In other words, association defines the multiplicity between objects. You may be aware of one-to-one, one-to-many, many-to-one, many-to-many all these words define an association between objects. Aggregation is a special form of association. Composition is a special form of aggregation.
http://javapapers.com/wp-content/uploads/2010/06/association.jpg
Example: A Student and a Faculty are having an association.
Aggregation
Aggregation is a special case of association. A directional association between objects. When an object ‘has-a’ another object, then you have got an aggregation between them. Direction between them specified which object contains the other object. Aggregation is also called a “Has-a” relationship.
http://javapapers.com/wp-content/uploads/2010/06/aggregation.jpg
Composition
Composition is a special case of aggregation. In a more specific manner, a restricted aggregation is called composition. When an object contains the other object, if the contained object cannot exist without the existence of container object, then it is called composition.
http://javapapers.com/wp-content/uploads/2010/06/composition.jpg
Example: A class contains students. A student cannot exist without a class. There exists composition between class and students.
Difference between aggregation and composition
Composition is more restrictive. When there is a composition between two objects, the composed object cannot exist without the other object. This restriction is not there in aggregation. Though one object can contain the other object, there is no condition that the composed object must exist. The existence of the composed object is entirely optional. In both aggregation and composition, direction is must. The direction specifies, which object contains the other object.
Example: A Library contains students and books. Relationship between library and student is aggregation. Relationship between library and book is composition. A student can exist without a library and therefore it is aggregation. A book cannot exist without a library and therefore its a composition. For easy understanding I am picking this example. Don’t go deeper into example and justify relationships!
Abstraction
Abstraction is specifying the framework and hiding the implementation level information. Concreteness will be built on top of the abstraction. It gives you a blueprint to follow to while implementing the details. Abstraction reduces the complexity by hiding low level details.
Example: A wire frame model of a car.
Generalization
Generalization uses a “is-a” relationship from a specialization to the generalization class. Common structure and behaviour are used from the specializtion to the generalized class. At a very broader level you can understand this as inheritance. Why I take the term inheritance is, you can relate this term very well. Generalization is also called a “Is-a” relationship.
http://javapapers.com/wp-content/uploads/2010/06/generalization.jpg
Example: Consider there exists a class named Person. A student is a person. A faculty is a person. Therefore here the relationship between student and person, similarly faculty and person is generalization.
Realization
Realization is a relationship between the blueprint class and the object containing its respective implementation level details. This object is said to realize the blueprint class. In other words, you can understand this as the relationship between the interface and the implementing class.
http://javapapers.com/wp-content/uploads/2010/06/realization.jpg
Example: A particular model of a car ‘GTB Fiorano’ that implements the blueprint of a car realizes the abstraction.
Dependency
Change in structure or behaviour of a class affects the other related class, then there is a dependency between those two classes. It need not be the same vice-versa. When one class contains the other class it this happens.
http://javapapers.com/wp-content/uploads/2010/06/dependency.jpg
Example: Relationship between shape and circle is dependency.


Tuesday, May 10, 2011

Threads In JAVA.............

QUESTIONS
1. Write a Java program to create three threads namely A, B, C and make them run one after another. (C has to run after B completes, B has to run after A completes).
2. What happens when a thread calls notify() but no thread(s) is waiting?
3. How will you declare a timer variable that will be accessed by multiple threads very frequently?
4. How will you synchronize static variables?
5. What happens when threads are waiting, but never being notified?
ANSWERS:
1. Many ways to do it. I prefer join(). When a thrad A calls b.join(), then A runs only after thread b completes. So, for this problem, C has to call b.join() and B has to call a.join()
2. Actually…, nothing :) the notify() call simply returns.
3. Declare the variable as volatile. Every thread caches a copy of instance variable, work with local copy, and then sync it with master copy. But, threads do not cache a copy of volatile instance variable.
4. Obtain class level lock. synchronized( obj.getClass()) {……..}
5. Leaving the answer to readers! :)

serialVersionUID


Give the use and an example of the scenario where you would use serialVersionUID in a your Java class?

Ans) During object serialization, the default Java serialization mechanism writes the metadata about the object, which includes the class name, field names and types, and superclass. This class definition is stored as a part of the serialized object. This stored metadata enables the deserialization process to reconstitute the objects and map the stream data into the class attributes with the appropriate type
Everytime an object is serialized the java serialization mechanism automatically computes a hash value. ObjectStreamClass’s computeSerialVersionUID() method passes the class name, sorted member names, modifiers, and interfaces to the secure hash algorithm (SHA), which returns a hash value.The serialVersionUID is also called suid.
So when the serilaize object is retrieved , the JVM first evaluates the suid of the serialized class and compares the suid value with the one of the object. If the suid values match then the object is said to be compatible with the class and hence it is de-serialized. If not InvalidClassException exception is thrown.
Changes to a serializable class can be compatible or incompatible. Following is the list of changes which are compatible:
•Add fields
•Change a field from static to non-static
•Change a field from transient to non-transient
•Add classes to the object tree
List of incompatible changes:
•Delete fields
•Change class hierarchy
•Change non-static to static
•Change non-transient to transient
•Change type of a primitive field
So, if no suid is present , inspite of making compatible changes, jvm generates new suid thus resulting in an exception if prior release version object is used .
The only way to get rid of the exception is to recompile and deploy the application again.
If we explicitly metion the suid using the statement:
private final static long serialVersionUID =
then if any of the metioned compatible changes are made the class need not to be recompiled. But for incompatible changes there is no other way than to compile again.

Java Collections API Interview Questions

1. You need to insert huge amount of objects and randomly delete them one by one. Which Collection data structure is best pet?
2. What goes wrong if the HashMap key has same hashCode value?
3. If hashCode() method is overridden but equals() is not, for the class ‘A’, then what may go wrong if you use this class as a key in HashMap?
4. How will you remove duplicate element from a List?
5. How will you synchronize a Collection class dynamically?
ANSWERS:

1. Obviously, LinkedList.
2. It leads to ‘Collision’ wherein all the values are stored in same bucket. Hence, the searching time increases quad radically.
3. Left to Readers.
4. Add the List elements to Set. Duplicates will be removed.
5. Use the utility method 
REference :http://excusemeworld.com/java-j2ee-interview-questions/java-collections-api-interview-questions/

Monday, May 9, 2011