Monday, July 29

ITEM 25: PREFER LISTS TO ARRAYS

                             PREFER LISTS TO ARRAYS


Reason:

Lists, if implemented correctly, can save us from ClassCastException but arrays can not.

How does that happen ?

lets start it with a statement

List in invariant while arrays are covariant .

Now what is this invariant covariant difference

read the difference quickly here

http://efectivejava.blogspot.in/2013/07/what-is-covarient-and-invarient.html

Let's go through a simple example

Let's declare and instantiate an array

Object[] objectArray = new Integer[1];

assign a string value to first place in array

objectArray[0] = "str";

What happens here. This does not fail at compile time although it will throw arrayStoreException at runtime

Now let us declare and instantiate a list

List<Object> ol = new ArrayList<Integer>();

assign a string value to first place in list
ol.add("str");

what happens here. It won't compile at all. Compiler will complain You can not store String in Integer type list. So it is providing opportunity to amend the program at compile time itself instead of having a surprised burst at runtime.


Conclusively Arrays provide runtime type safety while List provides compile time type safety and we always wish to identify the error at earliest opportunity. So List should be preferred over Arrays from type safety perspective although on performance scale there can be different views depending upon the specific scenario and uage in code.

What is compare and swap and compare and set (CAS)

What is compare and swap (CAS) and compare and set(CAS) in java?

In multithreaded java programming when a shared resource is accessed by multiple threads concurrently shared data needs to be synchronized for access and  visibility. But synchronization enforce locking and block all the threads but one trying to access the resource  This is optimistic approach of enforcing single access to shared resource at one time but it results huge degradation in multithreaded environment 

So there is one optimistic approach that is CAS - compare and swap

compare and swap?

What happens here is that a thread approach a shared resource with three variables 

a) current expected value
b) new value
c) memory address of the resource

So thread will access data from memory address will compare the current value with current expected value . If they match It will update the variable to new value. Obviously If multiple threads try making this operation simultaneously only one thread will succeed and others will fail. But other threads will not block instead invoker can continue with other operation or try the same again with failing threads. So this provides a lot better performance

and what is Compare and Set ?

Compare and Set is same as compare and swap . Only difference is that it returns a Boolean value as well which determines if operation succeeded or not. 

Top Java interview questions

Coming soon...  top 99 interview questions in java j2ee

ExecutorService in java concurrency package

What is ExecutorService in java?

Executorservice is nothing but a threadpool. Threadpool is nothing but a pool of threads. Threads are nothing but Runnable or callable tasks. Runnable task is nothing but an instance of class that implements Runnable interface. Callable task is nothing but an instance of class that implements callable interface

For example :

// runnable task
public class Drive implements Runnable {
    public void run(){
    }
}

//callable task
public class Drag implements Callable{
     public string call(){
   }
}

Now If you want to run a thread How would you do that . Simple traditional way to do that is :

Public class tester{
   public static void main(string args[]){
       new Drive().start();
   }
}

Here we are executing just one thread. 

What will we do If we have to get 10 task done in parallel and for that we require to execute more than 1 thread in parallel?

For such kind of requirements threadpool is very helpful and provide very simple mechanism to execute multiple threads in parallel.

Executorservice exec=Executors.newFixedThreadPool(8);

There are multiple implementations of ExecutorService available.


  •  Single thread executor   // only one thread in the pool
  •  cached thread Pool        // cache the thread created once. terminate the thread if thread remains unused in cache for 60 seconds
  •  Fixed Thread Pool          // fixed count of thread
  • Scheduled Thread Pool  // to schedule the future task
  • Single Thread Scheduled Pool  //only one thread to schedule future task



Now if you want to submit multiple task simply what you can do is :

ExecutorService pool= Executors.newFixedThreadPool(10);
      for (int i=0;i<20;i++){
            pool.submit(new Drag().start());
       }

Once this task is done you can terminate this threadpool just by invoking shutdown() method:

pool.shutdown();

We can implment any complex logic using ExecutorSerive and the code that we need to write is very simple . Also Executor service provide in built mechanism to control the overall execution process. 

We can also use Future interface to get the return value from each thread execution and then caculate the all Future values returnd. 

In above example we could retrieve the all future results by using below code :

List<Future<String>> futures = new ArrayList<Future<String>>(10);
     for(int i = 0; i < 10; i++){
futures.add(pool.submit(new Drag()));
}
    for(Future<String> future : futures){
String result = future.get();

   //Compute the result
}

And you can imagine what complex and error prone code you would have written by using existing API (pre- 1.5 version).




Item 22: Favor static member classes over nonstatic

             Favor static member classes over non static

What is static member class?

A nested class declared with static keyword

A non-static class has no static keyword with it .

What is major difference?

Non- static member class can't be referred standalone. It can be accessed with enclosing class only.
So when an instance of non-static class is created association with its enclosing class it created itself

And that cost extra time of instance initiation and also extra memory space for association. This association may not be required at all.

So one should always prefer static member class As that does not create any association with enclosing class.

So non-static member class should be created only when association with enclosing class is actually required i.e. there is some dependency on other part of the class as well along with member class Otherwise static member class is enough.

That saves not only time but also space So deliver great performance.