Friday, April 16, 2010

Simple and Runnable Code Samples for Java5 features

As I was working with a lot of Java 5 enhancements and had written some simple, runnable examples for demoing lot of the new features in Java 5, wanted to share the code samples for anyone who would like to use them to learn those features




Auto Boxing/Unboxing and the advanced for loop


package com.sreekanth.java5; 
import java.util.ArrayList;
import java.util.Iterator;

public class TrialAutoBoxUnBox { 

    public static void main(String[] args) {
       
        ArrayList myList= new ArrayList();
       
        //Java 1.4you would have done myList.add (new Integer(0));        
        myList.add (0);
        myList.add (1);
       
        //Pre-JDK 5 for loop
        for (Iterator i = myList.iterator(); i.hasNext(); )
        {
            //Java 1.4 you should cast the return to the Integer type
            System.out.println(i.next());
        }

        //another for loop - Post Java-1.5
        for (Integer num : myList)
        {
            System.out.println("i >>" + num);
        }
    }

}
 

Enumerated Types

package com.sreekanth.java5;
public class TrialEnumeratedType {
   
    // create an enumerated type - Java 5
    public enum MyTypes {CREATE, EDIT, DELETE, VIEW};
    public static void main(String[] argv) {
       
        // the enhanced for loop can easily iterate through the contents of the enumerated type
        for (MyTypes type : MyTypes.values())
            System.out.println(type);   
    }
}


Concurrency features - Executor

package com.sreekanth.java5;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import com.sreekanth.java5.util.TestRunnable;;

public class TrialExecutor {
    public static void main(String[] args) {
       
        // create multiple runnable
        TestRunnable t1 = new TestRunnable("t1");
        TestRunnable t2 = new TestRunnable("t2");
       
        // Executor
        ExecutorService executor = Executors.newFixedThreadPool(3);

        // start threads and place in runnable state
        executor.execute(t1);
        executor.execute(t2);

        // shutdown worker threads
        executor.shutdown();
           
    }
}



Runnable Class used by the Executor

package com.sreekanth.java5.util;

import java.util.Random;

public class TestRunnable implements Runnable {
    private int sleepTime;
    private String threadName;

    private static Random randomMaker = new Random();

    public TestRunnable(String name) {
        threadName = name;
        sleepTime = randomMaker.nextInt(5000);
    }

    public void run() {
        try {
            // The Java 5 printf function
            System.out.printf("%s going to sleep for %d milliseconds.\n",     threadName, sleepTime);
 

            Thread.sleep(sleepTime);
        }

        catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.printf("%s done sleeping\n", threadName);
    }
}


Generics and collections

package com.sreekanth.java5;

import java.util.ArrayList;
import java.util.Iterator;

import com.sreekanth.java5.dto.TestDTO;

/**
 * @author sreekanth
 *
 */
public class TrialGenerics {

    /**
     * @param args
     */
    public static void main(String[] args) {
       
        //Declare a Generic Collection - Aids in the compile time checking of the type
        ArrayList dtoList = new ArrayList();
       
        TestDTO d1 = new TestDTO("sreekanth", "d1");
        TestDTO d2 = new TestDTO("sreekanth", "d2");
        TestDTO d3 = new TestDTO("sreekanth", "d3");
       
        dtoList.add(d1);
        dtoList.add(d2);
        dtoList.add(d3);
       
        TrialGenerics myTrial = new TrialGenerics();
       
        myTrial.myHelperMethod(dtoList);
       
    }
   
    private void myHelperMethod (ArrayList mydtoList)
    {
        //Iterator iterator = mydtoList.iterator();
        for (Iterator iter = mydtoList.iterator(); iter.hasNext(); )
        {
            // No need to cast any more !!!
            TestDTO item = iter.next();
            System.out.println(item.getName());
            System.out.println(item.getType());           
        }
    }

}
 


TestDTO class used by the above program



package com.sreekanth.java5.dto;

public class TestDTO {
   
    String name;
    String type;
   
    public TestDTO(String name, String type) {
        super();
        this.name = name;
        this.type = type;
    }
   
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }
   
   

}


Static Imports

package com.sreekanth.java5;

import static java.lang.Math.*;
import static java.lang.System.out;

public class TrialStaticImport {

    public static void main(String[] args) {
        // No need for System..out
        out.println("Hi this is a static import example");

    }
}


Callable and Futures - Callable Class

package com.sreekanth.java5.util;
import java.util.concurrent.Callable;

public class TestCallable implements Callable
{
    private String threadName;
   
    @Override
    public Long call() throws Exception {
        long sum = 0;
        //sums up some numbers
       
        System.out.println("This is coming from " + this.threadName );
       
        for (long i = 0; i <= 100; i++) {
            sum += i;
        }
       
        System.out.println("This is the sum from the worker :" + this.threadName + "and the sum is :"  + sum);
        return sum;
    }
   
    public TestCallable(String name) {
        threadName = name;
    }
}


Use of Callable and Future in a Test Program

package com.sreekanth.java5;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.Callable;
import com.sreekanth.java5.util.TestCallable;

/**
 * @author sreekanth
 *
 */
public class TrialFutureNCallable {

    public static void main(String[] args) {

        //thread pool of size 10
        ExecutorService executor = Executors.newFixedThreadPool(10);       
        List> list = new ArrayList>();
       
        for (int i = 0; i < 20000; i++) {
            Callable worker = new TestCallable("t" + i);
                                   
            Future submit = executor.submit(worker);           
            list.add(submit);
           
        }
       
        long sum = 0;
        System.out.println(list.size());
       
        // Now retrieve the result
        for (Future future : list)
        {
            try {
                sum += future.get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
       
        System.out.println(sum);
    }
}

No comments: