Monday, July 29

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.

All about Anonymous Class


What is Anonymous class?

A class having no name is anonymous class. It falls in the family of nested classes in java. It is also called inner class

How is it different from a normal class?

1. It is not a member of enclosing class
2. Wherever it has to be used it is declared and instantiated there itself.
3. These classes can't extend any class and can't implement any interface.

What is the Use of Inner class?

You want to create a class on the fly. For example

to create comparators in a class where to want to sort objects list based on certain object properties

to create process objects such as Thread ,TimerTask,Runnable

These are very short lived and useful where we don't want classes or instances to live for long and wish to quickly use that and remove .