Tuesday, January 26, 2016

Thread Groups , Priority and Scheduler

Thread Group

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.



Example code,

public class ThreadGroupDemo implements Runnable{
 
public void run() {
          System.out.println(Thread.currentThread().getName());
    }
 
    public static void main(String[] args) {

          ThreadGroupDemo runnable = new ThreadGroupDemo();
     
ThreadGroup tg1 = new ThreadGroup("Parent ThreadGroup");
         
          Thread t1 = new Thread(tg1, runnable,"one");
          t1.start();
          Thread t2 = new Thread(tg1, runnable,"two");
          t2.start();
          Thread t3 = new Thread(tg1, runnable,"three");
          t3.start();
             
          System.out.println("Thread Group Name: "+tg1.getName());
         tg1.list();

    }
   }
 
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]



Thread Priorities
  • Each thread have a priority.
  • Priorities are represented by a number between 1 and 10. 
  • In most cases, thread scheduler schedules the threads according to their priority (known as preemptive scheduling). But it is not guaranteed because it depends on JVM specification that which scheduling it chooses.

3 constants defiend in Thread class:

public static int MIN_PRIORITY

public static int NORM_PRIORITY

public static int MAX_PRIORITY

Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and the value of MAX_PRIORITY is 10.


Example of priority of a Thread:

class TestMultiPriority1 extends Thread{

 public void run(){

   System.out.println("running thread name is:"+Thread.currentThread().getName());
   System.out.println("running thread priority is:"+Thread.currentThread().getPriority());

  }

 public static void main(String args[]){

  TestMultiPriority1 m1=new TestMultiPriority1();
  TestMultiPriority1 m2=new TestMultiPriority1();
  m1.setPriority(Thread.MIN_PRIORITY);
  m2.setPriority(Thread.MAX_PRIORITY);
  m1.start();
  m2.start();
 
 }
}  


Output:
       running thread name is:Thread-0
       running thread priority is:10
       running thread name is:Thread-1

       running thread priority is:1


Thread Scheduler 

Thread scheduler in java is the part of the JVM that decides which thread should run.

There is no guarantee that which runnable thread will be chosen to run by the thread scheduler.

Only one thread at a time can run in a single process.

The thread scheduler mainly uses preemptive or time slicing scheduling to schedule the threads.

Difference between preemptive scheduling and time slicing

Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence.

Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks.

 The scheduler then determines which task should execute next, based on priority and other factors.




Threads

A thread is a lightweight sub process, a smallest unit of processing. It is a separate path of execution.

Threads are independent, if there occurs exception in one thread, it doesn't affect other threads. It shares a common memory area.

what is thread in java
Thread is executed inside the process.

Thread life cycle


Ways of creating threads in java


Example 1,

Implements Runnable interface,


class MyThread implements Runnable
{
 public void run()
 {
  System.out.println("concurrent thread started running..");
 }
}

class MyThreadDemo
{
 public static void main( String args[] )
 {
  MyThread mt = new MyThread();
  Thread t = new Thread(mt);
  t.start();
 }
}
Output : concurrent thread started running..
By Extending Thread class,

class MyThread extends Thread
{
 public void run()
 {
  System.out.println("Concurrent thread started running..");
 }
}

classMyThreadDemo
{
 public static void main( String args[] )
 {
  MyThread mt = new  MyThread();
  mt.start();
 }
}
Output : concurrent thread started running..
Note on creating threads,

Using the Thread class directly has the following disadvantages.
  • Creating a new thread causes some performance overhead
  • Too many threads can lead to reduced performance, as the CPU needs to switch between these threads.
  • You cannot easily control the number of threads, therefore you may run into out of memory errors due to too many threads.



Multitasking

Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize the CPU. Multitasking can be achieved by two ways:

  • Process-based Multitasking(Multiprocessing)
  • Thread-based Multitasking(Multi threading)

1) Process-based Multitasking (Multiprocessing)

  • Each process have its own address in memory i.e. each process allocates separate memory area.
  • Process is heavyweight.
  • Cost of communication between the process is high.
  • Switching from one process to another require some time for saving and loading registers, memory maps, updating lists etc.

2) Thread-based Multitasking (Multithreading)

  • Threads share the same address space.
  • Thread is lightweight.
  • Cost of communication between the thread is low.

Process vs. threads


A process runs independently and isolated of other processes. It cannot directly access shared data in other processes. The resources of the process, e.g. memory and CPU time, are allocated to it via the operating system.

A thread is a so called lightweight process. It has its own call stack, but can access shared data of other threads in the same process. Every thread has its own memory cache. If a thread reads shared data it stores this data in its own memory cache. A thread can re-read the shared data.
A Java application runs by default in one process. Within a Java application you work with several threads to achieve parallel processing or asynchronous behavior.

Concurrency issues

  • Lost of update
  • Running behind each other
  • Shared access - Dead lock
Deadlock