Monday, 4 April 2016

Groovy XML traverse

Now we have some XML and we need to print out the subfield's code and text under datafield with tag 852.  In this case, the output expected is [b PIC, h test2]

 class XmlTraverse {  
   def String xml = """  
     <response>  
       <marcRecord>  
         <leader>00167nx a22000854 4500</leader>  
         <controlfield tag="001">4000089</controlfield>  
         <controlfield tag="004">3569260</controlfield>  
         <controlfield tag="005">20160330130804.0</controlfield>  
         <controlfield tag="008">1603300u  0  4000uueng0000000</controlfield>  
         <datafield ind2=" " ind1="8" tag="852">  
           <subfield code="b">PIC</subfield>  
           <subfield code="h">test2</subfield>  
         </datafield>  
         <datafield tag="954" ind1="" ind2="">  
           <subfield code="a">NLA</subfield>  
         </datafield>  
       </marcRecord>  
     </response>  
   """ 
 }  

First attempt, find the 852 tag datafield, under that datafield, find all subfields, use collect to transform to a List

 import groovy.util.XmlSlurper  
 import groovy.util.slurpersupport.GPathResult  
 import groovy.util.slurpersupport.NodeChild  
 import groovy.util.slurpersupport.NodeChildren;  
 class XmlTraverse   
   def test(){  
     def response = new XmlSlurper().parseText(xml)  
     def datafield852 = response.marcRecord.'*'.find { node->  
       node.name() == 'datafield' && node.@tag == '852'  
     }  
     def subfields = datafield852.'*'.findAll { node ->  
       node.name() == 'subfield'  
     }  
     def subfieldsCodeAndValue = subfields.collect { node ->  
       "" + node.@code + " " + node.text()  
     }  
     println subfieldsCodeAndValue  
   }  
 }  

It's bad because A. It's too long,  B. if the tag doesn't exist, it throws a ClassCastException.

Here come the 2nd attempt. Find all the subfields with a parent's tag value equal to 852. Now even if tag 852 didn't exist, it would not break, printing out an empty list.

   def test2(){  
     def response = new XmlSlurper().parseText(xml)  
     def List subfieldsValue = response.marcRecord.datafield.subfield.findAll { node->  
       node.parent().@tag == '852'  
     }.collect{"" + it.@code + " " + it.text()}  
     println subfieldsValue  
   }  

If we just to want to print the text, we can take advantage of the asterisk operator.

   def test3(){  
     def response = new XmlSlurper().parseText(xml)  
     def List subfieldsValue = response.marcRecord.datafield.subfield.findAll { node->  
       node.parent().@tag == '852'  
     }*.text()  
     println subfieldsValue  
   }  

Reference: Processing XML

Sunday, 3 April 2016

Synchronized block is Reentrant

A thread that has already acquired the lock of a synchronized block can freely enter another synchronized block, provided both synchronized blocks are locked on same object.

If a thread calls outer(), it can also call inner() from inside outer(), because both methods are synchronized on the same monitor object ("this")

 public class Reentrant{  
  public synchronized outer(){  
   inner();  
  }  
  public synchronized inner(){  
   //do something  
  }  
 }  


A customer lock can prevent reentrant. Now the thread calling outer() will be blocked at lock.lock() inside the inner() method.

 public class Lock{  
  private boolean isLocked = false;  
  public synchronized void lock()  
  throws InterruptedException{  
   while(isLocked){  
    wait();  
   }  
   isLocked = true;  
  }  
  public synchronized void unlock(){  
   isLocked = false;  
   notify();  
  }  
 }  

 public class NotReentrant{  
  Lock lock = new Lock();  
  public outer(){  
   lock.lock();  
   inner();  
   lock.unlock();  
  }  
  public synchronized inner(){  
   lock.lock();  
   //do something  
   lock.unlock();  
  }  
 }  


Reference: Locks in Java

Saturday, 2 April 2016

Static member class vs. nonstatic

Wherever you use a static member class, you can always remove the static keyword, and it still works. But it will have an unnecessary reference to the enclosing instance (the Outer class's instance)

If we add static on Inner class, it won't compile. Because static member class doesn't know about Outer class's instance.

 public class Outer {  
   public void doit(){  
     Inner inner = new Inner();  
     inner.doit();  
   }  
   private void doitAgain(){  
     System.out.println("do it again");  
   }  
   private class Inner {  
     public void doit() {  
       Outer.this.doitAgain();  
     }  
   }  
   public static void main(String[] args){  
     new Outer().doit();  
   }  
 }  

Friday, 1 April 2016

Callback

Suppose you want to check the progress of some work. You can choose to query the status from the server regularly. But this solution sucks right? It's like asking taxi driver every 5 minutes how far away the destination is.

 class Server{  
   private int progress;  
   public int getProgress(){ return progress;  }  
   public void copy() {  
     while(progress <100){  
       try{  
         Thread.sleep(10);  
         progress++;  
       }catch(InterruptedException e){}  
     }  
   }  
 }  
 public class NoCallbackClient {  
   private Server server = new Server();  
   public void call() {  
     server.copy();  
   }  
   public static void main(String[] args) throws InterruptedException{  
     final NoCallbackClient client = new NoCallbackClient();  
     Runnable r = ()->client.call();  
     new Thread(r).start();  
     System.out.print("Progress: ");  
     while(true){  
       int progress = client.server.getProgress();  
       Thread.sleep(200);  
       if(progress >= 100){  
         break;  
       }else{  
         System.out.print(progress+"% ");  
       }  
     }  
   }  
 }  

So instead of keeping asking the taxi driver, you should say to the driver, "Hey, let me know when we are 25%, 50%, 75% into our journey".

Here is what callback does.

 package callback;  
 interface IClient{  
   void callback(int i);  
 }  
 class Server{  
   private IClient client;  
   public Server(IClient client) {  
     this.client = client;  
   }  
   public void copy() {  
     for(int i=0;i<=100;i++){  
       if (i%10 == 0) {  
         client.callback(i);  
       }  
     }  
   }  
 }  
 public class CallbackClient implements IClient{  
   public void call() {  
     new Server(this).copy();  
   }  
   @Override public void callback(int i) {  
     System.out.print(i+"% ");  
   }  
   public static void main(String[] args){  
     new CallbackClient().call();  
   }  
 }  

Reference: http://blog.csdn.net/yqj2065/article/details/39481255

Wednesday, 30 March 2016

Volatile and double-checked locking

https://en.wikipedia.org/wiki/Singleton_pattern#Java_5_solution

This is a lazy initialization of singleton.

What does volatile do here?

1:  public final class SingletonDemo {  
2:    private static volatile SingletonDemo instance;  
3:    private SingletonDemo() { }  
4:    public static SingletonDemo getInstance() {  
5:      if (instance == null ) {  
6:        synchronized (SingletonDemo.class) {  
7:          if (instance == null) {  
8:            instance = new SingletonDemo();  
9:          }  
10:        }  
11:      }  
12:      return instance;  
13:    }  
14:  }  
Well, volatile ensures one thread can always read the up-to-date value of the variable updated by another thread.

What happens if we remove volatile?

OK, brain exercise time. Suppose two threads A and B come to this getInstance() method.

At time 100: Both A and B arrive at line 5
At time 101: A enters the synchronized block, B waits outside
At time 105: A exits the synchronized block at line 12
At time 106: B enters the synchronized block at line 7

Question: For thread B, is 'instance' equal to null now? Not necessarily without the volatile keyword. It might still seem to be null to B although it has in fact been assigned some value.

Next question: is there any advantage of using double-checked lock over the following implementation, which looks much neater.
1:  public final class SingletonDemo {  
2:    private static SingletonDemo instance = null;  
3:    private SingletonDemo() { }  
4:    public static synchronized SingletonDemo getInstance() {  
5:      if (instance == null) {  
6:        instance = new SingletonDemo();  
7:      }  
8:      return instance;  
9:    }  
10:  }  

I guess when the number of threads is high, the 2nd implementation is slower because of the synchronized keyword on the method. For the 1st implementation, once the object has been created, the synchronized block won't be executed at all.

Tuesday, 29 March 2016

Builder pattern

Quick template code

 public class FullName {  
   private final String firstName;  
   private final String lastName;  
   public static class Builder{  
     private String firstName;  
     private String lastName;  
     public Builder(){}  
     public Builder firstName(String firstName){  
       this.firstName = firstName;  
       return this;  
     }  
     public Builder lastName(String lastName){  
       this.lastName = lastName;  
       return this;  
     }  
     public FullName build(){  
       return new FullName(this);  
     }  
   }  
   private FullName(Builder builder) {  
     firstName = builder.firstName;  
     lastName = builder.lastName;  
   }  
 }  

Client code

 FullName name = new FullName.Builder().firstName("Ming").lastName("Sun").build();  

Finalizer guardian

"Effective Java" Item 7: Avoid finalizer

In the last few paragraphs, a concept of 'Finalizer guardian' is introduced. It took me a while to get my head around it. So I would like to share my understanding.

When we override a class's finalize() method, it is important we call super.finalize(), because its super class may want to close some critical resources. However, people don't always remember to call super.finalize(). Here the finalizer guadian comes to rescue.

Let's have a look at an example. OK, here we forget to call super.finalize()

 public class FooSub extends Foo {  
   @Override  
   protected void finalize() throws Throwable {  
     System.out.println("FooSub garbage collected");  
   }  
 }  

But with finalizer Guardian, everything is still under control.

 public class Foo {  
   private CriticalResource criticalResource = new CriticalResource();  
   private final Object finalizerGuardian = new Object(){  
     @Override  
     protected void finalize() throws Throwable {  
       System.out.println("Critical resource closed");  
       criticalResource.close();  
     }  
   };  
   private static class CriticalResource implements Closeable{  
     public void close() throws IOException {  
     }  
   }  
 }  


 public static void main(String[] args) {  
     FooSub foo = new FooSub();  
     foo = null;  
     System.gc();  
   }  

Check the output

 Critical resource closed
 FooSub garbage collected