Monday, September 23, 2013

How to convert an Array to a List object?

converting an Array to List: 

The below code shows you how to convert an Array to List object

code snippet:
 
        String[] str=new String[2];
        str[0]="nagarjuna";
        str[1]="kalyan";
       
        List<String> lstr=Arrays.asList(str);
       
        for(String s:lstr){
            System.out.println(s);
        }//end


The resultant is the List<String> type object, And the object 'lstr' is an implementation is of ArrayList type.
But this ArrayList is not expected ArrayList that availables in java.util.ArrayList.

This ArrayList is a private inner class in Arrays class.

If we observe the below code snippet, we can understand what is going in the back ground.

code snippet:
        System.out.println(lstr instanceof java.util.ArrayList);
        System.out.println(lstr.getClass().getName());//end

If we run the above code, we get the output like

o/p:
false
java.util.Arrays$ArrayList


So the implementation of the List is of type ArrayList which is available in the package java.util.Arrays$ArrayList



Please give your feedback at nagarjuna.lingala@gmail.com



Difference between Sorted and Ordered collections ?


Generally we have Collection implementations like ArrayList, Vector, HashSet...etc.

But we have four kind of collections ...

1) Ordered Collection
2) UnOrdered Collection
3) Sorted Collection
4) UnSorted Collection

If we know what is Ordered and Sorted collection, We can understand all the above 4 collections.

Ordered Collection:
  When a Collection is ordered, It means you can iterate through the collection in a specific (not-random) order.
- A HashTable collection is not ordered.
- An ArrayList keeps the order established by the element's index position.
- LinkedHashSet keeps the order established by insertion, so the last element inserted is the last element in the LinkedHashSet.
- Some collections that keep an order referred to as the natural order of the elements, and those collections are then not just ordered, but also sorted.

collection implementations order properties:
TreeMap - Sorted
LinkedHashMap - By insertion order or  last access order.
TreeSet - Sorted
LinkedHashSet - By insertion order
ArrayList - By index
Vector - By index
LinkedList - By index



Sorted Collection:
The order in the collection is determined according to some rule or rules, known as the sort order.

Sorting is done based on properties will figure out what order to put them in, based on the sort order.
Most commonly, the sort order used is something called the natural order.

collection implementations order properties:
TreeMap - By natural order or custom comparison rules
TreeSet - By natural order or custom comparison rules

Sunday, September 22, 2013

What is Singleton and Usage of It? and How to use System.gc() and Runtime.gc() ( Garbage Collection) ?

Hi All,

In this post, I am going to show you Two examples

1 - Example program for limiting objects creation using factory method style    (Singleton).
2 - Usage of System.gc() using the above example.


1) Limiting Object's creation: (requirement is creation of objects to a class is 7 only)

ObjectFactory7.java:

package com.nagarjuna.core.singletons;

public class ObjectFactory7 {

    private static int objcount = 0;

    private ObjectFactory7() {

    }

    public static ObjectFactory7 getInsance() throws ObjectCreationException {

        ObjectFactory7 obj = null;
        //
        if (objcount < 7) {
            obj = new ObjectFactory7();
            objcount++;
        } else {
            throw new ObjectCreationException();
        }
        return obj;
    }

    @Override
    protected void finalize() throws Throwable {// decrease the count of objcount for
                                                // Garbage Collection of each
                                                // object
        objcount--;
    }

    public static void showNumberOfObjects() {
        System.out.println("no of objects created from this factory are :"+ objcount);
    }

}//end class


ObjectCreationException.java:
package com.nagarjuna.core.singletons;

public class ObjectCreationException extends Exception {

    @Override
    public void printStackTrace() {
        System.out.println("Object creation exception occured, Creation of objects is limited to sevev (7) only..");
    }

}//end class

ObjCreationTest.java
package com.nagarjuna.core.singletons;

public class ObjCreationTest {

    public static void main(String[] args) {

        ObjectFactory7 o1, o2, o3, o4, o5, o6, o7, o8;

        try {

            ObjectFactory7.showNumberOfObjects();
            //
            o1 = ObjectFactory7.getInsance();
            ObjectFactory7.showNumberOfObjects();
            //
            o2 = ObjectFactory7.getInsance();
            ObjectFactory7.showNumberOfObjects();
            //
            o3 = ObjectFactory7.getInsance();
            ObjectFactory7.showNumberOfObjects();
            //
            o4 = ObjectFactory7.getInsance();
            ObjectFactory7.showNumberOfObjects();
            //
            o5 = ObjectFactory7.getInsance();
            ObjectFactory7.showNumberOfObjects();
            //
            o6 = ObjectFactory7.getInsance();
            ObjectFactory7.showNumberOfObjects();
            //
            o7 = ObjectFactory7.getInsance();
            ObjectFactory7.showNumberOfObjects();
            System.out.println("-----------------------------------------------");
            //
            o1 = null;

            ObjectFactory7.showNumberOfObjects();
            //
            o8 = ObjectFactory7.getInsance();//trying to create 8th object
            ObjectFactory7.showNumberOfObjects();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}//end class

If we try to run the above code we get an exception at 8th object creation code. we made o1 unreachable (null) and must be garbage collected.

output:
no of objects created from this factory are :0
no of objects created from this factory are :1
no of objects created from this factory are :2
no of objects created from this factory are :3
no of objects created from this factory are :4
no of objects created from this factory are :5
no of objects created from this factory are :6
no of objects created from this factory are :7
-----------------------------------------------
no of objects created from this factory are :7
Object creation exception occured, Creation of objects is limited to seven (7) only..

___________________________________________________________________________________________

The above code is an example for both Singleton and Limit Objects creation.





2) Usage of System.gc() :

ObjCreationTest.java:


package com.nagarjuna.core.singletons;

public class ObjCreationTest {

    public static void main(String[] args) {

        ObjectFactory7 o1, o2, o3, o4, o5, o6, o7, o8;

        try {

            ObjectFactory7.showNumberOfObjects();
            //
            o1 = ObjectFactory7.getInsance();
            ObjectFactory7.showNumberOfObjects();
            //
            o2 = ObjectFactory7.getInsance();
            ObjectFactory7.showNumberOfObjects();
            //
            o3 = ObjectFactory7.getInsance();
            ObjectFactory7.showNumberOfObjects();
            //
            o4 = ObjectFactory7.getInsance();
            ObjectFactory7.showNumberOfObjects();
            //
            o5 = ObjectFactory7.getInsance();
            ObjectFactory7.showNumberOfObjects();
            //
            o6 = ObjectFactory7.getInsance();
            ObjectFactory7.showNumberOfObjects();
            //
            o7 = ObjectFactory7.getInsance();
            ObjectFactory7.showNumberOfObjects();
            System.out.println("-----------------------------------------------");
            //
            o1 = null;
            // System.gc();
            Thread.sleep(500);
            ObjectFactory7.showNumberOfObjects();
            //
            o8 = ObjectFactory7.getInsance();//trying to create 8th object
            ObjectFactory7.showNumberOfObjects();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}//end class

When we try to run the above code, exception will be raised.

If we observe the above code in ObjectFactory7.java, It has finalize() method and by using this method we can decrease the count of objcount.

But we will get an exception, It means Garbage Collector is not guaranteed for garbage collection, and also we can't force the GC to collect the unreachable object.

But we can ask the GC to collect the unreachable object to be garbage collected by adding code System.gc() after below statement.

o1 = null;


Now try to run the above code with out Thread.sleep(500), Still we get the same exception. It means Calling System.gc() is also useless.

Since GC is a daemon service with the thread priority of 5 and runs in the background, But when we try to execute System.gc(), the GC will try to remove the memory of the unreachable object after some time ( must give some amount of time like  Thread.sleep(10) or (1) also). The GC will work perfectly.

Now  uncomment System.gc(), also keep Thread.sleep(500) and then run the code.
You won't get the exception and the count also decreases and the new object creation code also will be executed successfully.

Try it once.

Please give your feedback at nagarjuna.lingala@gmail.com


What happens when we try to override run() method in any Thread's child class and call start() method and by passing a reference of Runnable object to this Thread Object?

Thread's run() and Runnable's run() together:

Hi All,
In this post I am trying to show you what happens when I try to run a thread by passing a Runnable object to it and also override run() method in it.

below is the code snippet:


A.java  

package com.nagarjuna.core.threads;

public class A extends Thread {

    A(Runnable r) {// constructor
        super(r);
    }

    @Override
    public void run() {
        System.out.println("this run is from extends thread class A");
    }
}//end class


B.java 

package com.nagarjuna.core.threads;

public class B implements Runnable {

    @Override
    public void run() {
        System.out.println("this run is from implements Runnable class B");
    }
}//end class


Test.java

package com.nagarjuna.core.threads;

public class Test {

    public static void main(String[] args) {

        B b = new B();
        A a = new A(b);
        a.start();
    }
}//end class


Suppose, if we try to execute the above code, what output we get.

we get the
 output:  this run is from extends thread class A




where the Runnable's run()'s statement has gone. Here the thread is neglecting the Runnable object 'b' and ignoring run() method. The thread is executing A's (Thread) run()'s statements.

If we see the source code in Thread class source code, We see below code inside of run() method.

code snippet:

public void run() {

        if (target != null) {
            target.run();
        }

    }//end run()

here the variable target is nothing but the passed Runnable object, here 'b' is runnable object.And code should execute the b's run() method.

Until here is ok, But still the thread is executing a's run().

It is because of Inheritance in java, we have overridden run() method of Thread class, It means that we are specifying that we are giving new feature to threads run(). So, The JVM calls the run() method of class A and neglects the run() code of class B.

If we want to run both the run() methods, simply add super.run() at the beginning or end of the run() method in class A.

code snippet:

A.java

package com.nagarjuna.core.threads;

public class A extends Thread {

    A(Runnable r) {// constructor
        super(r);
    }

    @Override
    public void run() {
        super.run();
        System.out.println("this run is from extends thread class A");
    }
}//end class

now we get the output like
output:  this run is from implements Runnable class B
                 this run is from extends thread class A



I think you got my point. Here, due to inheritance property in java we are unable to run both 'a' and 'b' run() methods. We can run both of these run() methods using the super keyword.


Please give your feedback on this post at nagarjuna.lingala@gmail.com or javaojavablog@googlegroups.com


source: http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/Thread.java#Thread.run%28%29