Showing posts with label threads. Show all posts
Showing posts with label threads. Show all posts

Wednesday, October 10, 2012

Java Concurrency / Multithreading: Part 3

In Previous post (Java Concurrency / Multithreading :Part 2) learn how to initialize and use ExecutorService.

There are numerous problem domains where while designing the application you will need to implement the thread pool and each thread after completing the task, based on inputs should return a value. Futures and Callables exist exactly to solve this area.

Till now we have implemented the thread pool (in previous post) using the Runnables which do not return any value. In case a thread should return a value based on computation or work done as part of task you can use java.util.concurremt.Callable. Callable return value after execution. Callable returns an object of java.util.concurrent.Future. Future is used to check the status of task and return some value. Below is the example to use Callable and return a value

public class MyRunnable implements Callable<Long> {  
     @Override  
     public Long call() throw Exception {  
       return 5L;  
     }  
   } 

Using the Executor Framework

public class Example {

    public static void main(String[] args) {



        ExecutorService executor = Executors.newFixedThreadPool(5);

        List<Future<Long>> fList = new ArrayList<Future<Long>>();

        for (int i = 0; i < 999; i++) {

            Callable<Long> worker = new MyRunnable();

            Future<Long> submit = executor.submit(worker);

            fList.add(submit);

        }

        long sum = 0;



        for (Future<Long> future : fList) {

            try {

            sum += future.get();

            } catch (InterruptedException e) {

            e.printStackTrace();

            } catch (ExecutionException e) {

            e.printStackTrace();

            }

        }

        System.out.println("Final Sum is : " + sum);

        executor.shutdown();

    }

} 

Java Concurrency / Multithreading: Part 2

See my earlier post (Java Concurrency / Multithreading :Part 1) related to basics about java threads and concurrency.

Executor Framework

ThreadPools is the way to manage the pool of working threads and limit the creation of thread as creating a thread have resource overhead associates with it. Thus thread pools contains a work queue waiting for their turn to get executed.

In thread pool, the thread are constantly running and checking the queue for new work. As soon as the pool have a idle thread the work is assigned to one of the threads.

With Java 5 came Executor Framework under java.util.concurrent package, so that you do not need to create and manage your own pool e.g java.util.concurrent.Executor can be initialized as Executors.newfixedThreadPool(n) to create n worker threads. 

Like wise Executors.newSingleThreadExecutor(); will create a single thread pool with only one worker thread.

Example:
Creating a Runnable class
public class MyRunnable implements Runnable {
    private final long count;
    MyRunnable(long count) {
        this.count = count;
    }
    @Override
    public void run() {
        long mySum = 0;
        for (long i = 1; i < count; i++) {
            mySum = mySum + i;
        }
        System.out.println(mySum);
    }
}

Using the Executor Framework
public class Example {

    public static void main(String[] args) {

        ExecutorService executor = Executors.newFixedThreadPool(5);

        for (int i = 0; i < 100; i++) {

            Runnable myworker = new MyRunnable(99999999L + i);

            executor.execute(myworker);

        }

        executor.shutdown();

        while (!executor.isTerminated()) {



        }

        System.out.println("Completed processing the work queue");

    }

} 


ExecutorService executor = Executors.newFixedThreadPool(5); creates a new pool of 5 worker threads.

executor.execute(myworker); adds new work in the queue for thread pool to complete.

executor.shutdown(); waits till all the work in the queue is completed. After calling this method the ExecutorService will not take any new task but once all the current tasks in the queue are complete the ExecutorService will shutdown.

To stop the ExecutorService immediately call shutdownNow() method.This will attempt to stop all executing tasks right away, and skips all submitted but non-processed tasks. There are no guarantees given about the executing tasks. Perhaps they stop, perhaps the execute until the end. It is a best effort attempt.

 executor.isTerminated() checks if the service is terminated or not.

Till now we have submitted the tasks to ExecutorService and never waited to get a return value after . Thus in case the threads should return some value then you should use java.util.concurrent.Callable. See my next post (Java Concurrency / Multithreading: Part 3) summarizing the above concept.

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