Pages

Monday, 15 May 2017

Thread Pool and Thread Group

Java Thread Pool

Java Thread pool represents a group of worker threads that are waiting for the job and reuse many times.
In case of thread pool, a group of fixed size threads are created. A thread from the thread pool is pulled out and assigned a job by the service provider. After completion of the job, thread is contained in the thread pool again.

Advantage of Java Thread Pool

Better performance It saves time because there is no need to create new thread.

Real time usage

It is used in Servlet and JSP where container creates a thread pool to process the request.

Example of Java Thread Pool

Let's see a simple example of java thread pool using ExecutorService and Executors.
File: WorkerThread.java
  1. import java.util.concurrent.ExecutorService;  
  2. import java.util.concurrent.Executors;  
  3. class WorkerThread implements Runnable {  
  4.     private String message;  
  5.     public WorkerThread(String s){  
  6.         this.message=s;  
  7.     }  
  8.      public void run() {  
  9.         System.out.println(Thread.currentThread().getName()+" (Start) message = "+message);  
  10.         processmessage();//call processmessage method that sleeps the thread for 2 seconds  
  11.         System.out.println(Thread.currentThread().getName()+" (End)");//prints thread name  
  12.     }  
  13.     private void processmessage() {  
  14.         try {  Thread.sleep(2000);  } catch (InterruptedException e) { e.printStackTrace(); }  
  15.     }  
  16. }  
File: JavaThreadPoolExample.java
  1. public class TestThreadPool {  
  2.      public static void main(String[] args) {  
  3.         ExecutorService executor = Executors.newFixedThreadPool(5);//creating a pool of 5 threads  
  4.         for (int i = 0; i < 10; i++) {  
  5.             Runnable worker = new WorkerThread("" + i);  
  6.             executor.execute(worker);//calling execute method of ExecutorService  
  7.           }  
  8.         executor.shutdown();  
  9.         while (!executor.isTerminated()) {   }  
  10.   
  11.         System.out.println("Finished all threads");  
  12.     }  
  13.  }  

Output:
pool-1-thread-1 (Start) message = 0
pool-1-thread-2 (Start) message = 1
pool-1-thread-3 (Start) message = 2
pool-1-thread-5 (Start) message = 4
pool-1-thread-4 (Start) message = 3
pool-1-thread-2 (End)
pool-1-thread-2 (Start) message = 5
pool-1-thread-1 (End)
pool-1-thread-1 (Start) message = 6
pool-1-thread-3 (End)
pool-1-thread-3 (Start) message = 7
pool-1-thread-4 (End)
pool-1-thread-4 (Start) message = 8
pool-1-thread-5 (End)
pool-1-thread-5 (Start) message = 9
pool-1-thread-2 (End)
pool-1-thread-1 (End)
pool-1-thread-4 (End)
pool-1-thread-3 (End)
pool-1-thread-5 (End)
Finished all threads

ThreadGroup in Java

Java provides a convenient way to group multiple threads in a single object. In such way, we can suspend, resume or interrupt group of threads by a single method call.

Note: Now suspend(), resume() and stop() methods are deprecated.

Java thread group is implemented by java.lang.ThreadGroup class.

Constructors of ThreadGroup class

There are only two constructors of ThreadGroup class.
No.ConstructorDescription
1)ThreadGroup(String name)creates a thread group with given name.
2)ThreadGroup(ThreadGroup parent, String name)creates a thread group with given parent group and name.

Important methods of ThreadGroup class

There are many methods in ThreadGroup class. A list of important methods are given below.
No.MethodDescription
1)int activeCount()returns no. of threads running in current group.
2)int activeGroupCount()returns a no. of active group in this thread group.
3)void destroy()destroys this thread group and all its sub groups.
4)String getName()returns the name of this group.
5)ThreadGroup getParent()returns the parent of this group.
6)void interrupt()interrupts all threads of this group.
7)void list()prints information of this group to standard console.
Let's see a code to group multiple threads.
  1. ThreadGroup tg1 = new ThreadGroup("Group A");   
  2. Thread t1 = new Thread(tg1,new MyRunnable(),"one");     
  3. Thread t2 = new Thread(tg1,new MyRunnable(),"two");     
  4. Thread t3 = new Thread(tg1,new MyRunnable(),"three");    
Now all 3 threads belong to one group. Here, tg1 is the thread group name, MyRunnable is the class that implements Runnable interface and "one", "two" and "three" are the thread names.
Now we can interrupt all threads by a single line of code only.
  1. Thread.currentThread().getThreadGroup().interrupt();  

ThreadGroup Example

File: ThreadGroupDemo.java
  1. public class ThreadGroupDemo implements Runnable{  
  2.     public void run() {  
  3.           System.out.println(Thread.currentThread().getName());  
  4.     }  
  5.    public static void main(String[] args) {  
  6.       ThreadGroupDemo runnable = new ThreadGroupDemo();  
  7.           ThreadGroup tg1 = new ThreadGroup("Parent ThreadGroup");  
  8.             
  9.           Thread t1 = new Thread(tg1, runnable,"one");  
  10.           t1.start();  
  11.           Thread t2 = new Thread(tg1, runnable,"two");  
  12.           t2.start();  
  13.           Thread t3 = new Thread(tg1, runnable,"three");  
  14.           t3.start();  
  15.                
  16.           System.out.println("Thread Group Name: "+tg1.getName());  
  17.          tg1.list();  
  18.   
  19.     }  
  20.    }  
Output:
one
two
three
Thread Group Name: Parent ThreadGroup
java.lang.ThreadGroup[name=Parent ThreadGroup,maxpri=10]
    Thread[one,5,Parent ThreadGroup]
    Thread[two,5,Parent ThreadGroup]
    Thread[three,5,Parent ThreadGroup]

Java BlockingQueue Example

oday we will look into Java BlockingQueue. java.util.concurrent.BlockingQueue is a java Queue that support operations that wait for the queue to become non-empty when retrieving and removing an element, and wait for space to become available in the queue when adding an element.

Java BlockingQueue


Java BlockingQueue doesn’t accept null values and throw NullPointerException if you try to store null value in the queue.
Java BlockingQueue implementations are thread-safe. All queuing methods are atomic in nature and use internal locks or other forms of concurrency control.
Java BlockingQueue interface is part of java collections framework and it’s primarily used for implementing producer consumer problem. We don’t need to worry about waiting for the space to be available for producer or object to be available for consumer in BlockingQueue because it’s handled by implementation classes of BlockingQueue.
Java provides several BlockingQueue implementations such as ArrayBlockingQueueLinkedBlockingQueuePriorityBlockingQueueSynchronousQueue etc.
While implementing producer consumer problem in BlockingQueue, we will use ArrayBlockingQueue implementation. Following are some important methods you should know.
  • put(E e): This method is used to insert elements to the queue. If the queue is full, it waits for the space to be available.
  • E take(): This method retrieves and remove the element from the head of the queue. If queue is empty it waits for the element to be available.
Let’s implement producer consumer problem using java BlockingQueue now.

Java BlockingQueue Example – Message

Just a normal java object that will be produced by Producer and added to the queue. You can also call it as payload or queue message.

public class Message {
    private String msg;
    
    public Message(String str){
        this.msg=str;
    }

    public String getMsg() {
        return msg;
    }

}

Java BlockingQueue Example – Producer

Producer class that will create messages and put it in the queue.

import java.util.concurrent.BlockingQueue;

public class Producer implements Runnable {

    private BlockingQueue<Message> queue;
    
    public Producer(BlockingQueue<Message> q){
        this.queue=q;
    }
    @Override
    public void run() {
        //produce messages
        for(int i=0; i<100; i++){
            Message msg = new Message(""+i);
            try {
                Thread.sleep(i);
                queue.put(msg);
                System.out.println("Produced "+msg.getMsg());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //adding exit message
        Message msg = new Message("exit");
        try {
            queue.put(msg);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}

Java BlockingQueue Example - Consumer

Consumer class that will process on the messages from the queue and terminates when exit message is received.


import java.util.concurrent.BlockingQueue;

public class Consumer implements Runnable{

private BlockingQueue<Message> queue;
    
    public Consumer(BlockingQueue<Message> q){
        this.queue=q;
    }

    @Override
    public void run() {
        try{
            Message msg;
            //consuming messages until exit message is received
            while((msg = queue.take()).getMsg() !="exit"){
            Thread.sleep(10);
            System.out.println("Consumed "+msg.getMsg());
            }
        }catch(InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Java BlockingQueue Example - Service

Finally we have to create BlockingQueue service for producer and consumer. This producer consumer service will create the BlockingQueue with fixed size and share with both producers and consumers. This service will start producer and consumer threads and exit.

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class ProducerConsumerService {

    public static void main(String[] args) {
        //Creating BlockingQueue of size 10
        BlockingQueue<Message> queue = new ArrayBlockingQueue<>(10);
        Producer producer = new Producer(queue);
        Consumer consumer = new Consumer(queue);
        //starting producer to produce messages in queue
        new Thread(producer).start();
        //starting consumer to consume messages from queue
        new Thread(consumer).start();
        System.out.println("Producer and Consumer has been started");
    }

}
Output of the above java BlockingQueue example program is shown below.
Producer and Consumer has been started
Produced 0
Produced 1
Produced 2
Produced 3
Produced 4
Consumed 0
Produced 5
Consumed 1
Produced 6
Produced 7
Consumed 2
Produced 8
...
Java Thread sleep is used in producer and consumer to produce and consume messages with some delay.