Thursday 16 January 2014

What is VOLATILE in Java?

Java provides weaker form of synchronization called ‘volatile variable’ to ensure any update to variable is propagated to all other threads. Locking guarantees both visibility and atomicity but volatile only guarantees visibility.
The Visibility effect of volatile variables extends beyond the value of the volatile variable itself. When thread A writes to a volatile variable and subsequently thread B reads that same variable, the values of all variables that were visible to A prior to writing to volatile variable become visible to B after reading the volatile variable. So writing to a volatile variable works like entering into a synchronized block. However its not recommended to rely on volatile variables too heavily for visibility as it makes code more fragile and hard to understand.
Volatile variables are not thread safe for 64 bit operations as they are Non-atomic. Using volatile for 32 bit operations are fine but when you use it with 64 bit numeric variables, like double and long, JVM is permitted to divide 62 bit read or write operation into two 32 bit read or write operation. If read and writes are happening in two different threads its possible reader might read 32 bit updated value and 32 bit old value and overall unexpected dirty value as volatile doesn't guarantee atomicity. 
For atomic read-modify-write support Java provide 9 different flavors of Atomic Variables/References which can be used to overcome above problem.

Tuesday 2 July 2013

New Features in Java 7 : multi catch and multi throws Exceptions

Java 7 Introduced 2 brilliant features for Exceptions which can help to remove lots of boilerplate code in your project.  These features are
1. Multi catch Exceptions
2. Multi throws Exceptions

Prior to Java 7 one catch block can handle only one exception.

public void method(){
        try {
            // Some code that can throw one of catch exceptions
        } catch (Exception1 e) {
            e.printStackTrace();
        } catch (Exception2 e) {
            e.printStackTrace();
        } catch (Exception3 e) {
            e.printStackTrace();
        }
  }

But sometimes you handle more than of these exception in similar way so you end up repeating same catch block code for all exception.
From Java 7 one catch block can handle multiple exceptions with the help of pipes. So the same code will become like:

public void method(){
        try {
            // Some code that can throw one of catch exceptions
        } catch (Exception1 e | Exception2 e | Exception3 e) {
            e.printStackTrace();
             // If required you can define your exception handler and hadle exceptions as per there type in          
              handler
        }
    }


Second nice feature is multiple exceptions in throws section as method signature. Consider if you have just one Exception catch block for re-throw but you want to throw different type of exceptions to give user more granular access to thrown exception, prior to Java 7 you can not do so.
For example in below Example lets say if you want to tell user what ll type of exception this method can throw you can not do. You can only put top exception in hierarchy throw from method into method signature:

public void method(int i ) throws Exception {  // Can not tell FirstException or SecondException
        try {
            if(i<0){
                throw new FirstException();
            } else {
                throw new SecondException();
            }
             
        } catch (Exception e) {
            throw e;
        }
 }

Earlier it was not allowed/possible to put FirstException and SecondException together in Throws section of method signature. But from Java 7 compile has started doing more inclusive type checking so you can do that now which makes your method signature much more clear:

public void method(int i ) throws FirstException, SecondException{
        try {
            if(i<0){
                throw new FirstException();
            } else {
                throw new SecondException();
            }
             
        } catch (Exception e) {
            throw e;
        }
 }




Sunday 31 March 2013

Serializing Child with Parent not Serializable

This is interesting to see when you serialize a child which has one of the parent not serializable, on deserialization constructor of that parent class gets called.

In Given example while deserialization constructor of GrandParent will be called.

Note: While deserialization it calls only the default constructor of such parent. If non-serializable parent lack default constructor it will throw exception for "no valid constructor".

class Grandparent {
// must need default constructor
    public Grandparent() {
        System.out.println("A");
    }
}

 class Parent extends Grandparent implements Serializable {
    public Parent() {
        System.out.println("B");
    }
}
 class Child extends Parent {
    public Child() {
        System.out.println("C");
    }
}


public class TestSerialization{
    public static void main(String args[]) throws IOException, ClassNotFoundException {
        System.out.println("Serialization ....");
        ObjectOutputStream out = new ObjectOutputStream( new FileOutputStream("/object"));
        out.writeObject(new Child());
        System.out.println("Now Deserialization ....");
        ObjectInputStream in = new ObjectInputStream( new FileInputStream("/object"));
        Object obj = in.readObject();
        System.out.print(obj + " -- " + obj.getClass());
    }
}

OUTPUT
----------


Serialization ....
A
B
C
Now Deserialization ....
A
co.uk.sample.Child@d2906a -- class co.uk.sample.Child



Monday 11 March 2013

TestNG vs JUnit


Here are some features of TestNG which is not available in Junit
1. Method Dependency: In Junit execution of test methods is depends on order of string literals in method name. Its hard to maintain the ordering and its not visible if there is any dependency of one method on other method. On the Other hand in TestNG you can mention dependency using dependsOnMethods.
@Test ( dependsOnMethods = "testPreSettlement" )
public void testSettlement(){ ... }

In this case if first method fails, second method doesn't go in fail status but you will see it as skipped.

2. Parametric Testing (DDT): As data driven test framework TestNG  has feature of parametric testing where you can pass parameter to a test method using configuration. Junit needs more code to use this feature.
@testng.parameters value="param1, param2"
public void testSettlement(){ ... }

You can configure this in test suite file as below:
<!DOCTYPE suite SYSTEM "http://beust.com/testng/testng-1.0.dtd">
<suite name="settlement">
 <test name="testSettlement">
  <parameter name="param1" value="Admin"/>
  <parameter name="param2" value="2"/>
  <classes> 
   <class name="co.uk.SettlementTest"/>
  </classes>
 </test> 
</suite>

3. Ordering/Prioritiesing Test cases: In TestNG you can use Priority annotation to put ordering between test cases.
@Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
public @interface Priority { int value() default 0; }

For Example
@Priority(-1)
@Test
public void testSettlement(){ ... }

4. Grouping Tests and Repeatability:  In TestNg you can group tests, even configure number of times you want to execute particular test case. You can also set timeout for executing test method.
@Test(threadPoolSize = 4, invocationCount = 5,  timeOut = 10000, groups = { "functional"})

Tuesday 26 February 2013

Sample Socket Connection Example

Telnet Server Implementation Code:

class TelnetServer {
   private final ServerSocket serverSocket = new ServerSocket(4444);

   public void start(){
      try {
            log.info("Starting server on port " + serverSocket.getLocalPort());
            System.out.println("Starting server on port " + serverSocket.getLocalPort());
            while (isRunning && serverSocket != null) {
                log.info("Waiting for client connection!");
                System.out.println("Waiting for client connection!");
                Socket socket = serverSocket.accept();
                log.info("Creating new telnet client connection");
                System.out.println("Creating new client connection");
                connManager.createConnection(socket);// Create a thread to handle socket 
            }
        }
   }

}



ConnectionHandler Implementation Code:

class ConnectionHandler implements Runnable{


private final Socket socket;

public ClientConnection(){
          socket = new Socket("localhost", 4444);
}

@Override
public void run()

 try {
            iStream = new DataInputStream(socket.getInputStream());
            oStream = new DataOutputStream(socket.getOutputStream());
            out = new PrintWriter(socket.getOutputStream(), true);

            cmdContext = CommandContext.createInstance(new File("."),                               
            socket.getLocalAddress().getHostName(), socket.getInetAddress().toString());
            cmdExecutor = new CommandExecutor();
            System.out.println(cmdContext);

            while ((line = iStream.readUTF()) != null && !line.equals(".")) {
                input = input + line;
                System.out.println("Command Received: " + line);
                out.print(input);
                oStream.writeUTF(getCommandResponse(cmdContext, cmdExecutor, line));
             }
         }

    }
}

*********************************************************

TelnetClient implementation :


public class TelnetClient {
    public static void main(String args[]) throws Exception {
        Socket soc = new Socket("localhost", 4444);
        String Command;
        DataInputStream din = new DataInputStream(soc.getInputStream());
        DataOutputStream dout = new DataOutputStream(soc.getOutputStream());
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Welcome to Telnet Client");
        System.out.println("< Telnet Prompt >");
        while ((Command = br.readLine()) != null && !Command.equals(".")) {
            dout.writeUTF(Command);//sends command to server
            System.out.println(din.readUTF()); //gets the response of server
        }
        soc.close();
        din.close();
        dout.close();
        br.close();
    }
}

Monday 11 February 2013

Serialize Array in Java


For Serializing Array we can use ObjectOutputStream/ObjectInputStream classes.

NOTE: An ObjectInputStream deserializes primitive data and objects previously written using an ObjectOutputStream.


public class SerializeArray {
    public static void main(String[] args) {

        String[][] twoD = new String[][]{new String[]{"Alex", "Hyde"},
                new String[]{"Rohan", "Disuza"}};

        String[][] newTwoD = null; // will deserialize to this

        System.out.println("Before serialization");
        for (String[] arr : twoD) {
            for (String val : arr) {
                System.out.println(val);
            }
        }

        try {
            FileOutputStream fos = new FileOutputStream("test.dat");
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(twoD);

            FileInputStream fis = new FileInputStream("test.dat");
            ObjectInputStream iis = new ObjectInputStream(fis);
            newTwoD = (String[][]) iis.readObject();

        } catch (Exception e) {

        }

        System.out.println("After serialization");
        for (String[] arr : newTwoD) {
            for (String val : arr) {
                System.out.println(val);
            }
        }
    }
}


Tuesday 15 January 2013

When finally block is NOT called?


Finally block is NOT called in following conditions
  • If the JVM exits while the try or catch code is being executed, then the finally block may not execute. This may happen due to System.exit() call.
  • if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues.
  • If a exception is thrown in finally block and not handled then remaining code in finally block may not be executed.
  • If there is infinite loop, or deadlock then also finally block will not get executed