Sunday, October 6, 2013

Java Quiz - 2


1) What is volatile in java?               
Volatile is only applicable on variables in java ,not to methods. By making a variable as volatile , you are asking the JVM to read the values of the variable from the memory and not from the cache. Java reads and writes are atomic using volatile variable including  long and double variables. Using Volatile variable reduces the risk of memory inconsistency errors in java .An access to a volatile variable in Java never has chance to block, since we are only doing a simple read or write, so unlike a synchronized block we will never hold on to any lock or wait for any lock.

2) Why wait(), notify() and notifyall() methods are defined in Object class not in thread class?
Because Lock is placed on the object not on the calling Thread.

3)What are the differences between synchronized and volatile keyword in Java ?
Volatile keyword in java is a field modifier, while synchronized modifies code blocks and methods. Synchronized requires a lock to be placed on the object, where as volatile does not require any lock to be placed on the object. Other Threads will be blocked on the monitored area i.e. synchronized block or Synchronized method, whereas Volatile variables are not blocked. Synchronized method affects performance whereas Volatile doesn't affect performance as much as Synchronized. Since volatile keyword in Java only synchronizes the value of one variable between Thread memory  and "main" memory ,while synchronized synchronizes the value of all variable between thread memory and "main" memory and locks and releases a monitor to boot. Due to this reason synchronized keyword in Java is likely to have more overhead than volatile. Volatile can be applied on null, whereas Synchronized cannot be applied on null.

4)What is the difference between hash map and hash table in java?
 Hashmap is Synchronized, Hashtable is not Synchronized. Hashmap accepts one null key and multiple null values, where as hashtable doesn't  accept null keys and null values.

5) How HashMap can be Synchronized?
Map map = new HashMap(); It can be Synchronized using Collections.SynchronizedMap(map);

6)What are the design patterns you have worked on?
Singleton, Factory, MVC

7)What is Double checked Locking in Singleton?
Singleton pattern can be achieved in various ways in java.
·         Eager initialization
·         Lazy initialization
·         Double Checked Locking
 Eager initialization:- the instance is created much before it is required i.e. instance is created as static variable when the class is loaded all the static variables are created. So new instance also created. Please ensure that you are using volatile keyword on your instance variable , otherwise you enter into out of order write error.(This means, JVM has just allocated the memory for your instance, but not executed the constructor yet, so it may return null pointer exception or crash application with out of write error)
public class Singleton {
      private static volatile Singleton instance = new Singleton();
      // private constructor
      private Singleton() {
      }
      public static Singleton getInstance() {
      return instance;
      }
}  
Lazy Initialization: So to solve this problem, just declare the instance, and if the instance is null then only create a new instance. On the first call it checks if the instance is null, if the instance is null, then a new instance is created. if it is not null, the same instance is returned.
 public final class Singleton {
            private static volatile Singleton instance = null;
            // private constructor
            private Singleton() {
            } 
      public static Singleton getInstance() {
                  if (instance == null){
                        synchronized (Singleton.class) {
                              instance = new Singleton();
                        }
                  }
                  return instance;
                  }
            }
 but there is a problem with this method, two threads T1 and T2 comes to the block (instance== null) and both can create the instance of the Singleton class, so u need to have double checked locking.
public final class Singleton {
private static volatile Singleton instance = null;
// private constructor
private Singleton() {
} 
public static Singleton getInstance() {
            if (instance == null){
                  synchronized (Singleton.class) {
                         // Double check
                        if(instance == null){
                              instance = new Singleton();
                        }
                  }
            }
            return instance;
      }
}
 This is the Correct implementation of Double checked locking.


8)What is weak reference?
you create weak reference using
WeakReference weakWidget = new WeakReference(widget);
and then elsewhere in the code we can use
 weakWidget.get()
to get the actual widget object.
The weak reference isn't strong enough to prevent garbage collection, so you may find (if there are no strong references to the widget) that weakWidget.get() suddenly starts returning null. we use it in case if we want listeners to register it to the service. Listener objects are created as Weak references.

9)What is the difference b/w Action support and Action?
       Action is an interface which has only one method execute() and Some constants like LOGIN, ERROR , SUCCESS,INPUT, NONE.
ActionSupport is a class which extends Serializable,  validatable, ValidationAware Interfaces which provides methods for field level validation. E.g. validate() addFieldError(fieldname, Errormessage) .

10)What is the difference between OGNL and EL?
Object Graph Navigational Language is specific to Struts2
EL is specific to Servlets.
OGNL is more powerful and provides lambda expressions to navigate through objects in value stack. OGNL provides more sophisticated way to traverse through request, session, application and web context.

11) What is the dynamic method invocation in struts2?
In Struts2 , we can provide method name using method attribute,
<action name="getFormResult" class = "MyPackage.MyClass" method="myFormResult">
     <result name="Success" > /Success.jsp </result>
</action>

This can also be configured dynamically depending on the action name passed, using Action Wild cards ,For E.g.
<action name="get*Result" class = "MyPackage.MyClass" method="my{1}Result">
     <result name="Success" > /Success.jsp </result>
</action>
So whatever the value passed to the * will  be substituted to {1}


12)What is the difference b/w struts1 and struts2?
    In Struts1, we have not configured the controller as filter where as in struts 2 we have configured Struts2PrepareAndExecuteFlter as controller which is a filter.
So no need to provide <LoadOnStartup>1</LoadOnStartup> in Struts2.
Struts2 has some automatic features like event validation, automatic transfer of parameters from jsp form to value stack before the initialization of Action class so that the parameters are available to the Action class from input form. So it's a Pull MVC Architecture whereas in Struts1 , you need to push the objects from Form to Action class, and Action class needs to retrieve the values explicitly.
The Automatic features of struts2 is due to Interceptors where as the Struts1 doesn't have Interceptors concept.

13) Are interceptors threadsafe?
     No , Interceptors are not thread safe whereas action classes are thread safe. That's why when the request comes, a new instance of action class is created and we can store the data in the member variables as it is specific to the action class instance , where as in Servlets, Every request is Serviced by a different thread and the data stored in the servlet is shared by different threads So we use Request, session objects to pass the data from one form to other.

14)What is the flow of struts2 ? data flow ? or architecture?
When the user hits the URL, a jsp form is displayed which is either configured as the welcome file list or a url in the namespace. then the user fills the form and submits the data, the control is passed to container , the container looks at web.xml, web.xml has Struts2PrepareAndExecteFilter is configured as a filter, so Container calls the Controller and controller looks at the action mapper and invokes Action Proxy, Action proxy calls the Configuration Manager and looks at struts.xml, here the form's  method="" and action="" attributes are compared with the Action mappings , and appropriate  Action Class's information, and the interceptor's associated with the Action class is retrieved and control is passed to Action Invocation, Action Invocation is the big brother, it passes its own instance to Interceptor's invoke (ActionInvocation ai)method , and executes the pre-logic and post logic methods,
and finally the control is passed to Action class , Whose execute() method gets called. and the appropriate HttpResponse gets generated. This is passed to the client back.

15)What  is an Outer Join?
Outer join is of 2 types.
    1)Left join.
        Left join is the intersection of the 2 table and the left table.
        Select empno, empname from Employee
        LeftJoin Address
        On Employee.empid = Address.empid;
    2)Right join
        Its the intersection of 2 tables + the right table.
        Select empno,empname from Employee
        RightJoin Address
        On Employee.empid = Address.empid;

No comments:

Post a Comment