Monday, January 27, 2014

How to write a custom class loader

Under the Java™ 1 class loading system, it was a requirement that any custom class loader must subclass java.lang.ClassLoader and override the abstract loadClass() method that was in the ClassLoader. The loadClass() method had to meet several requirements so that it could work effectively with the JVM's class loading mechanism, such as:
  • Checking whether the class has previously been loaded
  • Checking whether the class had been loaded by the system class loader
  • Loading the class
  • Defining the class
  • Resolving the class
  • Returning the class to the caller
The Java 2 class loading system has simplified the process for creating custom class loaders. The ClassLoader class was given a new constructor that takes the parent class loader as a parameter. This parent class loader can be either the application class loader, or another user-defined class loader. This allows any user-defined class loader to be contained easily into the delegation model.
Under the delegation model, the loadClass() method is no longer abstract, and as such does not need to be overridden. The loadClass() method handles the delegation class loader mechanism and should not be overridden, although it is possible to do so, so that Java 1 style ClassLoaders can run on a Java 2 JVM.
Because the delegation code is handled in loadClass(), in addition to the other requirements that were made of Java 1 custom class loaders, custom class loaders should override only the new findClass() method, in which the code to access the new class repository should be placed. The findClass() method is responsible only for loading the class bytes and returning a defined class. The method defineClass() can be used to convert class bytes into a Java class:
   class NetworkClassLoader extends ClassLoader {
         String host;
         int port;

         public Class findClass(String name) {
             byte[] b = loadClassData(name);
             return defineClass(name, b, 0, b.length);
         }
         private byte[] loadClassData(String name) {
             // load the class data from the connection
         }
    }

Thursday, January 23, 2014

Difference between sleep() and wait()?

Call on:
  •     wait(): Call on an object; current thread must synchronize on the lock object.
  •     sleep(): Call on a Thread; always currently executing thread.
Synchronized:
  •     wait(): when synchronized multiple threads access same Object one by one.
  •     sleep(): when synchronized multiple threads wait for sleep over of sleeping thread.
Hold lock:
  •     wait(): release the lock for other objects to have chance to execute.
  •     sleep(): keep lock for at least t times if timeout specified or somebody interrupt.
Wake-up condition:
  •     wait(): until call notify(), notifyAll() from object
  •     sleep(): until at least time expire or call interrupt().
Usage:
  •     sleep(): for time-synchronization and;
  •     wait(): for multi-thread-synchronization.

Wednesday, January 22, 2014

How to make class immutable.


    1) Don’t provide “setter” methods  
    Setter methods are meant to change the state of object and this is what we want to prevent here.
    2) Make all fields final and private 
    Fields declared private will not be accessible outside the class and making them final will ensure the even accidentally you can not change them
    3) Declare class as final
     Don’t allow subclasses to override methods
    4) Attention with mutable instance variables in class
    Always remember that you can have either mutable  or immutable instance variables, identify them and return new objects with copied content for all mutable objects. Immutable variables can be returned safely without extra effort.

    1. Example :

      public final class Contacts {
          private final String name;
          private final String mobile;
          public Contacts(String name, String mobile) {
              this.name = name;
              this.mobile = mobile;
          }
        
          public String getName(){
              return name;
          }
        
          public String getMobile(){
              return mobile;
          }
      }

    Getting GUI error codes from third party system, converting Data base error code and storing in DB. Getting DB error codes and convert GUI error codes and show the error messages. To handle this witch collection frame work should we need to use?

    Solution:

    Use two HasMaps to solve this problem.

    HashMap hm1 = new HashMap();
    hm1.put("GUI Error codes","DB Error codes")

    HashMap hm2 = new HashMap();
    hm2.put("DB Error codes","GUI Error codes")

    Out put of of the below java file?

    public class Test {
        public void name(String s) {
            System.out.println("vgggg");
        }

        public void name(Number s) {
            System.out.println("mjj");
        }
       


        public static void main(String s[]) {

            Test test = new Test();
            test.name(null);
           
        }

    }
    Output :
    Compile error : The method name(String) is ambiguous for the type Tes

    Covariant return types in Java

    Java 1.5 supports covariant return types. What does this mean? Before 1.5, when you override a superclass method, the name, argument types and return type of the overrding method has to be exactly same as that of superclass method. Overriding method is said to be invariant with respect to argument types and return type.
    If you change any argument type, then you are not really overriding a method -- you are actually overloading it.
        class Shape {
            public void draw(Graphics g, int x, int y) {}
        }
    
        class Circle extends Shape {
            public void draw(Graphics g, float x, float y) {}
            // Circle.draw overloads the inheried Shape.draw 
            // -- argument types for 'x' and 'y' are different here.
        }
    
    Also, before 1.5, overriding method can't have different return type. This is relaxed in 1.5. The subclass method's return type R2 may be different from superclass method's return type R1, but R2 should be a subtype of R1. i.e., subclass can return type may be a subtype of superclass return type.
       class ShapeFactory {
            public Shape newShape() {}
       }
    
       class CircleFactory extends ShapeFactory {
            public Circle newShape() {}
       } 
    
    In the above example, CircleFactory.newShape returns Circle type -- which is subtype of superclass method's (ShapeFactory.newShape) return type. With 1.5, this is allowed. Method overriding is said to be covariant with respect to return type. Another example is clone method. Object.clone method returns Object type. A subclass such as Shape's clone method can return Shape type instead of Object type. Interestingly, exception declaration is already covariant even before 1.5. i.e., subclass method may throw either same types or subtypes of superclass method's exceptions.
    How is this implemented? Although the return type based overloading is not allowed by java language, JVM always allowed return type based overloading. JVM uses full signature of a method for lookup/resolution. Full signature includes return type in addition to argument types. i.e., a class can have two or more methods differing only by return type. javac uses this fact to implement covariant return types. In the above, CircleFactory example, javac generates code which is equivalent to the following:
    
    
    class CircleFactory extends ShapeFactory {
        public Circle newShape() {
           // your code from the source file
           return new Circle();
        }
        
        // javac generated method in the .class file
        public Shape newShape() {
           // call the other newShape method here -- invokevirtual newShape:()LCircle;
        } 
    }
    
    
    We can use javap with -c option on the class to verify this. Note that we still can't use return type based overloading in source language. But, this is used by javac to support covariant return types. This way, there is no change needed in the JVM to support covariant return types.

    When should we use intern method of String on String constants

    According to String.intern(), intern method is supposed to return the String from the String pool if the String is found in String pool, otherwise a new string object will be added in String pool and the reference of this String is returned.

    String s1 = "Rakesh";
    String s2 = "Rakesh";
    String s3 = "Rakesh".intern();
    String s4 = new String("Rakesh");
    String s5 = new String("Rakesh").intern();
    
    if ( s1 == s2 ){
        System.out.println("s1 and s2 are same");  // 1.
    }
    
    if ( s1 == s3 ){
        System.out.println("s1 and s3 are same" );  // 2.
    }
    
    if ( s1 == s4 ){
        System.out.println("s1 and s4 are same" );  // 3.
    }
    
    if ( s1 == s5 ){
        System.out.println("s1 and s5 are same" );  // 4.
    }
    will return:
    s1 and s2 are same
    s1 and s3 are same
    s1 and s5 are same

    Tuesday, January 21, 2014

    4 different ways to create objects in java:

    There are four different ways to create objects in java:

    A. Using new keyword This is the most common way to create an object in java. Almost 99% of objects are created in this way.

     MyObject object = new MyObject();

    B. Using Class.forName() If we know the name of the class & if it has a public default constructor we can create an object in this way.

    MyObject object = (MyObject) Class.forName("subin.rnd.MyObject").newInstance();

    C. Using clone() The clone() can be used to create a copy of an existing object.

    MyObject anotherObject = new MyObject();
    MyObject object = anotherObject.clone();


    D. Using object deserialization Object deserialization is nothing but creating an object from its serialized form.

    ObjectInputStream inStream = new ObjectInputStream(anInputStream );
    MyObject object = (MyObject) inStream.readObject();

    Threads



    1.If you have to write a thread based application in JAVA u will extend Thread class or implement Runnable interface?

    2.What is the difference between Vector and ArrayList in Java?Is Vector thread safe class?

    In the below code does using vector help in multithreading?

    Class
    {
    Vector v
    //2 threads that access v
    // add elements
    //remove elements
    //more code
    }
     
    Is this code thread safe ?
    3. synchronized class A
    {
    }
    will this compile?

    In one table we have 'GENDER' column, while data migration, we updated 'GENDER' column wrongly(inplace of M, we updated F .inplace of F, we updated M), I need a query to correct this..

    We need to write three queries, to solve this problem.
    Table Name = EMP
    Column name = GENDER
    1) Update EMP set GENDER='TEMP' where GENDER= 'M'
    2) Update EMP set GENDER='M' where GENDER= 'F'
    3) Update EMP set GENDER='F' where GENDER='TEMP'

    Collections


                  Can u write a custom ArayList such that u can add objects to it dynamically?

    How does hashing work in general?How are the multiple values in value part stored internally?

    When we write hashmap.get("key") what are the steps executed internally to get the value

    If you have a list of Employee objects each having an id, name and salary, how will you sort them based on name,how will you do?

    What is the difference between Comparable and Comparator in JAVA?

    What sorting method does Collections.sort() use internally?

    Interview Questions when 5 or 6 years of Java/J2EE experience

    Gemstone
    1. How would you implement your own Thread Pool.
    2. What is NIO
    3. Best way to read data from socket using traditional I/O
    4. Beat way to read file.
    5. How to read characters from InputStream.
    6. How Serialization works
    7. Synchronization
    8. how to implement counter in servlet.
    9. how hashtable is thread safe.
    10. CharSet, Enocder, Decoder
    11. AtomicInteger, volatile, transient.
    12. JTA, XA, how XA works, two phase commit.
    13. Role of transaction manager in XA transaction.
    14. XADataSource, and closing XADataSource.
    15. UserTransaction
    16. JCA Architecture

    Interview Questions when 5 or 6 years of Java/J2EE experience

    Nomura
    1. How would you implement cache in java.
    2. How would you implement auto complete using java, jsp.
    3. How would you implement a chache with auto complete feature.
    4. How to make class immutable.
    5. How to serialize immutable class.
    6. How to gaurantee message delivery in JMS, fault tolerance
    7. Message recovery techniques and redelivery.
    8. DROP table.
    9. Oracle Stored Procedure or function
    10. Struts architecture
    11. JSP Exception Handling
    12. java Objective SCJP Level
    13. java Design Pattern
    14. J2EE objective
    15. Implementing references
    16. UNIX Commands - grep, softlink, hardlink
    17. Serializable, Externalizable, Cloneable