Thursday, January 23, 2014

What is new in JDK versions ....5.0,6.0,7.0,8.0

Java is language with  specific syntax , data types , access control keywords like that is C and C++ .
Every language has its own grammar .But in case of java language syntax is changing less frequently but all utilities and libraries based on it are changing day by day .
It is not possible to tell that what new API is added say in collection framework etc .Now Java guys have gone and searched for libraries like STL in C++ and whatever they find in other language libraries  like in Python , Perl , Small Talk etc and they are going to add those more for more specific purpose .
There are tones of collection types already available in till Java 7 .

I have just aggregated links for updates but nowadays those API are unfortunately considered as knowledge of java as language so we should be well versed with using just libraries with  deft instead of writing new thing which might be error prone and waste of time and may be reinvention of wheel ...

Some questions you might face like
- What is difference between HashMap , ConcurrentHashMap , HashTable and Vector ?
- What is un-modifiable collection ?
- How to add run-time safety using checked API of collection ?
- How to remove repeated values in collection using Collections.Singleton
- What is load factor and initial capacity for Map ?
- how create collection with copy of same value multiple times ? - use nCopies
- how to sort and search collection ? (Java uses merge sort - stable sort - So some might ask to write custom search in Java using their interfaces )
- Some questions on GC tweeking and memory , algorithms for GC etc


This will go on ...but all this is based on choosing some API of language library

http://docs.oracle.com/javase/1.5.0/docs/relnotes/features.html#java.lang

5.0 was major release -



Java Language Features
Generics
Enhanced for Loop
Autoboxing/Unboxing
Typesafe Enums
Varargs
Static Import
Metadata (Annotations)

Base Libraries
Lang and Util Packages
Networking
Security
Internationalization
Improved Support for Environment Variables
ProcessBuilder
Formatter
Scanner
Reflection
JavaBeansTM Component Architecture
Collections Framework
Java API for XML Processing (JAXP)
Bit Manipulation Operations
Math
Instrumentation
Serialization
Concurrency Utilities
Threads
Monitoring and Management






Detailed chnages in collection package (Library ..)

http://docs.oracle.com/javase/1.5.0/docs/guide/collections/changes5.html


http://docs.oracle.com/javase/6/docs/technotes/guides/collections/changes6.html

Some changes in collection for 6.0

http://docs.oracle.com/javase/6/docs/technotes/guides/collections/changes6.html


http://www.oracle.com/technetwork/java/javase/jdk7-relnotes-418459.html


Java 8.0 is releasing in March 2014 ...so keep it up ...

You can check history from 1.0 also summarized till  future version 10  on Wikipedia - I don't want to increase content on internet by copying ..

http://en.wikipedia.org/wiki/Java_version_history



Tuesday, January 7, 2014

Java Clone - Deep Copy , Shallow Copy explained ..


Shallow Copy - All inheritance tree objects are not cloned just references are cloned .It still refer to old objects in hierarchy level .Changes in old  mutable objects will reflect .You might need to create clone of member objects and set in clone method.In that case all  object tree must implement clonable marker interface .Note that clone method does not invoke constructor or initialization blocks of class .It is just bianry copy of object .

Deep Copy (Serialization )- All inheritance tree are cloned /copied .Changes in mutable object state are not reflected as objects are different . All object tree must implement  "serializable" marker interface .
We have to take care of transient variables ourselves .

Need of serialization - To get object state in binary format and pass it over wire as 1's and 0's .So that it can be loaded in class loader of another JVM .

 package salpejava.clone;  
 import java.io.ByteArrayInputStream;  
 import java.io.ByteArrayOutputStream;  
 import java.io.IOException;  
 import java.io.ObjectInputStream;  
 import java.io.ObjectOutputStream;  
 import java.io.Serializable;  
 public class TestClone {  
      public static void main(String[] args) {  
           Person person = new Person();  
           Address address = new Address();  
           address.setAdress("OLD ADDRESS");  
           person.setId(10);  
           person.setAddress(address);  
           try {  
                Person shallowPerson = (Person) person.clone();  
                System.out.println(shallowPerson.toString());  
                address.setAdress("NEW ADDRESS");  
                System.out.println(shallowPerson.toString());  
           } catch (CloneNotSupportedException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
           }  
           Person person2 = new Person();  
           Address address2 = new Address();  
           address2.setAdress("OLD ADDRESS 2 ");  
           person2.setId(20);  
           person2.setAddress(address2);  
           Person clonedPerson2 = person2.getDeepCopy();  
           System.out.println(clonedPerson2.toString());  
           address.setAdress("NEW ADDRESS 2");  
           System.out.println(clonedPerson2.toString());  
      }  
 }  
 class Person implements Cloneable,Serializable {  
      /**  
       *   
       */  
      private static final long serialVersionUID = -1605117478578295247L;  
      private int id = 10;  
      private Address address;  
      public int getId() {  
           return id;  
      }  
      public void setId(int id) {  
           this.id = id;  
      }  
      public Address getAddress() {  
           return address;  
      }  
      public void setAddress(Address address) {  
           this.address = address;  
      }  
      @Override  
      public Object clone() throws CloneNotSupportedException {  
           return super.clone();  
      }  
      @Override  
      public String toString() {  
           return "Person [id=" + id + ", address=" + address + "]";  
      }  
      public Person getDeepCopy () {  
           Person deepPerson = null;  
           ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();  
           try {  
                ObjectOutputStream outputStream = new ObjectOutputStream(arrayOutputStream);  
                outputStream.writeObject(this);  
           } catch (IOException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
           }  
           ByteArrayInputStream arrayInputStream = new ByteArrayInputStream(arrayOutputStream.toByteArray());  
           ObjectInputStream inputStream;  
           try {  
                inputStream = new ObjectInputStream(arrayInputStream);  
                 deepPerson =  (Person)inputStream.readObject();  
           } catch (IOException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
           } catch (ClassNotFoundException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
           }  
           return deepPerson;  
      }  
 }  
 class Address implements Cloneable,Serializable {  
      /**  
       *   
       */  
      private static final long serialVersionUID = -4056104942549317741L;  
      private String adress = "";  
      public String getAdress() {  
           return adress;  
      }  
      public void setAdress(String adress) {  
           this.adress = adress;  
      }  
      @Override  
      public String toString() {  
           return "Address [adress=" + adress + "]";  
      }  
      @Override  
      protected Object clone() throws CloneNotSupportedException {  
           // TODO Auto-generated method stub  
           return super.clone();  
      }  
 }  


Java volatile variable explained ..

Volatile variable is used for communicating between threads so that value can be updated atomically and all thread can see same value at same time .

Real time use -
Suppose we have to stop application's all threads after pressing stop button . create "public static volatile boolean " flag and check that flag in each thread .Once value of that flag changes to "true" after pressing button all threads will see it changed  and they will quit as they check that flag say in loop .

volatile here is for atomic update of value .Means all threads will see changes value not corrupted one.All threads see same copy of data .Means it avoid to show past value to one thread and new value to another .So it is effective to pass value between threads and updates are atomic to all threads .

We can say it is lightweight synchronization .

Following code is just example but will not create corrupted value of volatile int :)

Volatile has happen before relationship with other thread means updated value is guaranteed to be displayed to all other threads .

In java long and double are not tread safe as they are constructed using other small types like group of bytes it involves two steps writing first half part then second half .So this operation of two step is not atomic .
But volatile double and volatile long are  guaranteed to be happen before and atomic so be  cautious while using long and  double in multi-threaded environments .

 package com.salpe.basic.Threads;  
 import java.util.Random;  
 public class TestThread {  
      public static volatile long test = 0;  
      public static Random randomGenerator = new Random();  
      public static void main(String[] args) {  
           Thread th1 = new Thread(new Runnable() {  
                @Override  
                public void run() {  
                     // TODO Auto-generated method stub  
                     for (int i = 0; i < 100; i++) {  
                                              System.out.println(Thread.currentThread().getName() + " Seen as " +test);  
                          try {  
                               Thread.sleep(100);  
                          } catch (InterruptedException e) {  
                               // TODO Auto-generated catch block  
                               e.printStackTrace();  
                          }  
                     }  
                }  
           });  
           Thread th2 = new Thread(new Runnable() {  
                @Override  
                public void run() {  
                     while (true) {  
                          // TODO Auto-generated method stub  
                          test = randomGenerator.nextInt();  
                          System.out.println(Thread.currentThread().getName() + " Changed to " +test);  
                          try {  
                               Thread.sleep(50);  
                          } catch (InterruptedException e) {  
                               // TODO Auto-generated catch block  
                               e.printStackTrace();  
                          }  
                     }  
                }  
           });  
           th1.start();  
           th2.start();  
      }  
 }