Tuesday, October 09, 2012

Java Concurrency / Multithreading :Part 1

Goal:

How to execute the tasks in background using Java concurrent programming. It also covers the concepts of threads, parallel programming, java.util.concurrent.Executor, java.util.concurrent.Future, java.util.concurrent.Callable framework.

Details:

What is Concurrency?

In computer world, concurrency means executing several programs simultaneously or in parallel and these programs may or may not interact with each other. Running several programs in parallel or asynchronously can add to over all performance of the task.

Process vs Threads

Both thread and process are methods of parallelizing the application. Below are the key points highlighting the differences between Process and Thread.

Process: are independent execution units. Applications are typically divided into various processes during the design phase. It cannot directly access shared data in other processes.However this is done by inter-process mechanism managed by operating system. A process might contain multiple threads.

Thread: are light weight processes and is the basic unit to which the operating system allocates processor time. A thread can execute any part of the process code, including parts currently being executed by another thread. . Every thread have its own memory cache.

Why Concurrency

  •  Efficient utilization of resources
  • Increased application throughput
  • High responsiveness
  •  Programs becomes simpler: as some of the problem domains are well suited to be represented as concurrent tasks

Disadvantages

  • With increased complexity the program design becomes more complex
  • Context Switching between threads, too many open threads will lead to context switching overheads causing the performance degrade

 Threads in Action

Threads are the core of all concurrent or parallel programing. There are 2 ways to implement thread in java.
The First one is extending java.lang.Thread class. Below is the way to create a thread:
Thread myThread =  new Thread();
Now after initialization , to start thread
myThread.start();

Create a subclass of Thread
public class CustomThread extends Thread{

 public void run(){
 System.out.println("Hello Thread");
}
}

Using the above class
CustomThread thread1 = new CustomThread();

thread1.start()
The second way is to implement the java.lang.Runnable interface.
public class MyRunnable implements Runnablee{
public void run (){

System.out.println("Hello Runnable"); 

} 

}
Using the above class
Thread thread1 =  new Thread(new MyRunnable);

thread1.start();
Next>>> Java Concurrency / Multithreading: Part 2


No comments:

Post a Comment