Search This Blog

Sunday, September 11, 2011

Creating JaxContext is slow

Recently, I need to create xml or json from a POJO.  I used JAXB and jettison to do the job.  At the beginning, I create the following class:

import java.io.Writer;

import javax.xml.bind.*;
import javax.xml.stream.XMLStreamWriter;

import org.codehaus.jettison.mapped.*;

public class BadJaxbPrinter {
    /**
     * To print an object to xml format
     * @param writer
     * @param jaxbAnnotedObj the object to be printed.  The class must be annoted with @XmlRootElement
     * @throws JAXBException
     */
    public void toXml(Writer writer, Object jaxbAnnotedObj) throws JAXBException {
        JAXBContext context = JAXBContext.newInstance(jaxbAnnotedObj.getClass());
        Marshaller marshaller = context.createMarshaller();
        marshaller.marshal(jaxbAnnotedObj, writer);
    }

    /**
     * To print an object to json format
     * @param writer
     * @param jaxbAnnotedObj the object to be printed.  The class must be annoted with @XmlRootElement
     * @throws JAXBException
     */
    public void toJson(Writer writer, Object jaxbAnnotedObj) throws JAXBException {
        Configuration config = new Configuration();
        MappedNamespaceConvention convention = new MappedNamespaceConvention(config);
        XMLStreamWriter xmlStreamWriter = new MappedXMLStreamWriter(convention, writer);
       
        JAXBContext context = JAXBContext.newInstance(jaxbAnnotedObj.getClass());
        Marshaller marshaller = context.createMarshaller();
        marshaller.marshal(jaxbAnnotedObj, xmlStreamWriter);
    }
}

However, the above implementation is really slow.  The reason is that it is slow to create JAXBContext because it uses reflection to parse the object's annotation.  Since JAXBContext is thread safe, it should be only created once and reuse it.  Here is the new version of implementation:

public class JaxbPrinter {
    private final MappedNamespaceConvention convention;
    //creating JaxbContext seems expensive, do NOT recreate it
    private final JAXBContext context;
   
    public JaxbPrinter(Class<?> clazz) throws JAXBException {
        Configuration config = new Configuration();
        convention = new MappedNamespaceConvention(config);
        context = JAXBContext.newInstance(clazz);
    }
    /**
     * To print an object to xml format
     * @param writer
     * @param jaxbAnnotedObj the object to be printed.  The class must be annoted with @XmlRootElement
     * @throws JAXBException
     */
    public void toXml(Writer writer, Object jaxbAnnotedObj) throws JAXBException {
        Marshaller marshaller = context.createMarshaller();
        marshaller.marshal(jaxbAnnotedObj, writer);
    }

    /**
     * To print an object to json format
     * @param writer
     * @param jaxbAnnotedObj the object to be printed.  The class must be annoted with @XmlRootElement
     * @throws JAXBException
     */
    public void toJson(Writer writer, Object jaxbAnnotedObj) throws JAXBException {
        XMLStreamWriter xmlStreamWriter = new MappedXMLStreamWriter(convention, writer);
        Marshaller marshaller = context.createMarshaller();
        marshaller.marshal(jaxbAnnotedObj, xmlStreamWriter);
    }
}
It is 25 times faster than the previous version with 10000 executions of  toXml.  Note that Marshaller and Unmarshaller are not thread safe and it is cheap to recreate them.

Also, toJson is 5 times slower than toXml.  Since the response time meets SLA, I didn't bother to use other JSON implementation (like jackson).

Monday, August 15, 2011

fail to install myql gem for ruby

You tried to install mysql gem on linux:

$ gem install mysql
Building native extensions.  This could take a while...
ERROR:  Error installing mysql:
	ERROR: Failed to build gem native extension.

/home/t/ruby-1.9.2-p136-1/bin/ruby extconf.rb
checking for mysql_ssl_set()... *** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers.  Check the mkmf.log file for more
details.  You may need configuration options.

Provided configuration options:
	--with-opt-dir
	--without-opt-dir
	--with-opt-include
	--without-opt-include=${opt-dir}/include
	--with-opt-lib
	--without-opt-lib=${opt-dir}/lib
	--with-make-prog
	--without-make-prog
	--srcdir=.
	--curdir
	--ruby=/home/t/ruby-1.9.2-p136-1/bin/ruby
	--with-mysql-config
	--without-mysql-config
/home/t/ruby-1.9.2-p136-1/lib/ruby/1.9.1/mkmf.rb:368:in `try_do': The complier failed to generate an executable file. (RuntimeError)
You have to install development tools first.
	from /home/t/ruby-1.9.2-p136-1/lib/ruby/1.9.1/mkmf.rb:435:in `try_link0'
	from /home/t/ruby-1.9.2-p136-1/lib/ruby/1.9.1/mkmf.rb:440:in `try_link'
	from /home/t/ruby-1.9.2-p136-1/lib/ruby/1.9.1/mkmf.rb:552:in `try_func'
	from /home/t/ruby-1.9.2-p136-1/lib/ruby/1.9.1/mkmf.rb:797:in `block in have_func'
	from /home/t/ruby-1.9.2-p136-1/lib/ruby/1.9.1/mkmf.rb:693:in `block in checking_for'
	from /home/t/ruby-1.9.2-p136-1/lib/ruby/1.9.1/mkmf.rb:280:in `block (2 levels) in postpone'
	from /home/t/ruby-1.9.2-p136-1/lib/ruby/1.9.1/mkmf.rb:254:in `open'
	from /home/t/ruby-1.9.2-p136-1/lib/ruby/1.9.1/mkmf.rb:280:in `block in postpone'
	from /home/t/ruby-1.9.2-p136-1/lib/ruby/1.9.1/mkmf.rb:254:in `open'
	from /home/t/ruby-1.9.2-p136-1/lib/ruby/1.9.1/mkmf.rb:276:in `postpone'
	from /home/t/ruby-1.9.2-p136-1/lib/ruby/1.9.1/mkmf.rb:692:in `checking_for'
	from /home/t/ruby-1.9.2-p136-1/lib/ruby/1.9.1/mkmf.rb:796:in `have_func'
	from extconf.rb:50:in `<main>'


Gem files will remain installed in /home/t/ruby-1.9.2-p136-1/lib/ruby/gems/1.9.1/gems/mysql-2.8.1 for inspection.
Results logged to /home/t/ruby-1.9.2-p136-1/lib/ruby/gems/1.9.1/gems/mysql-2.8.1/ext/mysql_api/gem_make.out
 
You need to check mkmf.log which is in the same folder as gem_make.out is in.  In my case, mkmf.log is in /home/t/ruby-1.9.2-p136-1/lib/ruby/gems/1.9.1/gems/mysql-2.8.1/ext/mysql_api/ 
 
Read mkmf.log, if you see something similar to below: 
 
/usr/bin/ld: skipping incompatible /usr/lib/libz.so when searching for -lz
/usr/bin/ld: skipping incompatible /usr/lib/libz.a when searching for -lz
/usr/bin/ld: cannot find -lz
collect2: ld returned 1 exit status
 
It means you have an incompatible zlib-devel binary.  In case, the 32-bit zlib-devel is installed, but not the 64 bits.  Run following command to fix it:

yum erase zlib-devel
yum install zlib-devel 

Thursday, June 23, 2011

Reverse a singly linked list

I was asked this question during an interview today.  I didn't do well though.  I guess because it was an interview, I had some pressure and could think fast and clearly.  In fact, this question is pretty easy with the recursive.  When I got home, it didn't take me too long to figure out the correct answer.  Here is the code in Java.

class Node {
    Node next;
}

class Util {
    public static void reverseNode(Node node) {
        reverseNode(node, null);
    }
   
    private static void reverseNode(Node node, Node previous) {
        if (node != null) {
            reverseNode(node.next, node);
            node.next = previous;
        }
    }
}

Update:

The recursive solution is easy to understand and implement.  However, you may get a StackOverflow exception if the list is big.  Here is the non-recursive solution:

class Util {
    public static void reverseNode(Node node) {
        Node previous = null;
        while (node != null) {
            Node next = node.next;
            node.next = previous;
            previous = node;
            node = next;
        }
    }
}

Tuesday, June 21, 2011

Swap 2 integers without using a temp variable

There are 2 ways to do it. 
  1. use sum of the 2 variables:
 void swap(int a, int b) {
       a = a + b;
       b = a - b;
       a = a - b
    }

     2. use bitwise operation (xor)
void swap(int a, int b) {
      a = a ^ b;
      b = a ^ b;
      a = a ^ b;
    }

Create Singleton in Java

A singleton is simply a class that is instantiated exactly once.  There are two approaches to create a singleton class.
  1. Early initialization,
  2. Lazy initialization.
 There are several ways to create singleton in each approach.

For early initialization:
  1. Singleton with public final field
public class Singleton {
      public static final Singleton INSTANCE = new Singleton();

      private Singleton() {
         //do something
      }

      public void someMethod() {
         // do something
      }
    }

     2. Singleton with static factory
public class Singleton {
     private static final Singleton INSTANCE = new Singleton();
     
     private Singleton() {
         //do something
     }

     public static Singleton getInstance(){
       return INSTANCE
     }

     public void someMethod() {
         // do something
     }   
   }
  
      3. Singleton with enum
public enum Singleton {
      INSTANCE;
            
      private Singleton() {
         //do something
      }

      public void someMethod() {

         // do something
      }    
    }


For lazy initialization:

  However unless you absolutely need it, don't use lazy initialization.

     1. Lazy initialization holder class idiom for static fields (a class will not be initialized until it is used)

public class LazySingleton {
     private static class SingletonHolder {
       static final LazySingleton INSTANCE = new LazySingleton();
     }
     
     private LazySingleton() {
         //do something
     }

     public static LazySingleton getInstance(){
       return SingletonHolder.INSTANCE;
     }

     public void someMethod() {
         // do something
     }
    }

 2. Double-check idiom for lazy initialization

   class LazySingleton {
     private static volatile LazySingleton instance;
     private LazySingleton(){

        //do something
     }


     public static LazySingleton getInstance() {
        if (instance == null) {
            synchronized (
LazySingleton.class) {
                if (instance == null) {
                    INSTANCE = new LazySingleton();
                }
            }
        }
        return instance;

     }
   }

Monday, June 20, 2011

Reverse the string word by word, in place

The idea is reverse the string character by character first, then reverse the word character by character.  For example, we have string "abc defg hijk".  The first step is to reverse the string character by character:

"abc defg hijk" ==> "kjih gfed cba"

Then reverse the word in the output string character by character:

"kjih gfed cba" ==> "hijk defg abc"

The run time is O(n) with constant extra space.  Here is the code in java:

    public static void resverseString(char[] input) {
        reverseString(input, 0, input.length - 1);
        int start = 0;
        int end = 0;
        for (char temp : input) {
            if (temp == ' ') {
                reverseString(input, start, end - 1);
                start = end + 1;
            }
            end++;
        }
        reverseString(input, start, end - 1);
    }
   
    private static void reverseString(char[] input, int start, int end) {
        while (start < end) {
            swap(input, start, end);
            start++;
            end--;
        }
    }
   
    private static void swap (char[] input, int i, int j) {
        char temp = input[i];
        input[i] = input[j];
        input[j] = temp;
    }

Wednesday, June 15, 2011

Weak Reference in Java

Today, during a phone interview, I was asked a question about WeakReference in Java.  I only knew that the weak referenced object can be garbage collected by JVM, and nothing more.  I did a little research, and realized that there are 4 types of references in Java:
  1. Strong Reference
  2. Soft Reference
  3. Weak Reference
  4. Phantom Reference
They are in the order from strong to weak references.  3 classes, SoftReference, WeakReference, and PhantomReference are for the last 3 references.  For strong reference, just use new operator. Below is a great blog talking about all 4 references:

Understanding Weak References