Showing posts with label Threads. Show all posts
Showing posts with label Threads. Show all posts

Sunday, December 8, 2013

The Lifecycle of a Thread in Java

Understanding the lifecycle of threads is very important while programming in Threads.

A Thread can be various states during its life time. The following diagram describes all the states a thread can undergo and the method calls that cause the transition from one state to another:


Java Thread States
  1. Runnable: A Thread starts its life from this state. Thread first enters into this state after the start() method of the thread is invoked. In this state, thread will be waiting for the scheduler to pick the thread for execution. The scheduler picks the threads based on their priorities. A thread can also re-enter this state either after running, waiting, sleeping or also while coming back from blocked state.
  2. Running: A thread is in running state means its currently running. There are several ways for thread to go into Runnable state. But there is only one way to come into Running state: the scheduler selects the thread for execution for the runnable pool. A thread runs until its swapped out, becomes blocked, or voluntarily give up its turn by invoking the static method Thread.yield().
  3. Dead: A thread enters this state when it completes execution. It may also enters this state when it is terminated by unrecoverable error condition. If a thread goes to this state means it can not be run again.
  4. Sleep: A Java thread may be forced to sleep (suspend) for some predefined time. In this state, thread is still alive but is not runnable, it might be return to runnable state later. It can throw InterruptedException.
  5. Blocked: A thread can enter blocked state because of waiting for the resources that are held by another thread.
    1. Blocked on I/O: Thread enters this state because of waiting for I/O resources. In this case, the thread will be sent back to Runnable state after the availability of resources.
    2. Blocked on Synchronization: Thread may enters this state while waiting for object lock. Thread will be moved to Runnable state after it acquires lock.
  6. Waiting state: A call to Object.wait() method causes the current object to wait. The thread remains in waiting state until some other thread invokes notify() or notifyAll() method of this object.

Release 5.0 introduced the Thread.getState() method, which results in one of the following Thread.State values:
  • NEW
  • RUNNABLE
  • BLOCKED
  • WAITING
  • TIMED_WAITING
  • TERMINATED
The Thread class API also introduced a method isAlive(), which returns true if the thread has already been started and not stopped. If the method isAlive() returns false, the thread is either New, or is Dead.

Tuesday, December 3, 2013

Concurrency in Java

If a system that allows to execute multiple tasks simultaneously that system is called a Concurrent System

The Java language and the JVM have been designed to support concurrent programming from the beginning. Since Java 5.0 version, it has also included high-level concurrency APIs in java.uti.concurrent packages. Also the later versions introduced updated versions of the existing APIs, also added several new APIs.

 

Processes and Threads:

 

  • In concurrent programming, there are two basic units of execution, called processes and threads. In Java, concurrent programming mainly concerned about threads.
  • A process has a self-contained execution environment. It generally has a complete private set of basic run-time resources, in particular, each process has its own memory space.
  • Threads are sometimes called as lightweight processes. Both processes and threads provide and execution environment, but creating new threads requires fewer resources than required for new processes.
  • Threads exist within a process. Every process has at least one thread
  • Threads share the process's resources, including memory and open files. 
  • Java Program runs in its own process and by default in one thread.


 Thread Basics:

  • A thread is a thread of execution. 
  • The JVM allows an application to have multiple threads of execution running concurrently. 
  • Each thread has a priority. Threads with higher priority are executed in preference to the threads with the lower priority. 
  • Each thread may or may not have also marked a Daemon
  • When a JVM starts up, there is usually a single non-daemon thread (which typically invokes the main method).
  • The JVM continues to execute the threads until either of the following occurs:
    • The exit method of Runtime class has been invoked and the security manager has allowed the exit method to execute.
    • All threads that are not daemon threads have died, either by returning from the run method call or by throwing an exception.

 

Creating and Running Threads:


Threads can be created in two ways: 
    • Extending Thread class and overriding run() method.
    • Building a class that implements Runnable interface and then creating an object of Thread class passing the Runnable object as a parameter.
Below is a simple example of creating threads using the second approach. This example creates 10 threads, each of the thread calculate and prints the multiplication tables from 1 to 10.

Steps to implement the example:
  • Create a class Name Calculator implementing Runnable interface.
public class Calculator implements Runnable
  • Declare a private int attribute named number and implement the constructor to initialize its value.
private int number;
  • Implement the run() method. This method calculates the multiplication table of the number.
@Override
 public void run() {
  for (int i = 1; i <= 10; i++) {
   System.out.printf("%s: %d * %d = %d\n", Thread.currentThread()
     .getName(), number, i, i * number);
  }
 }
  • Implement the main class of the application, which contains main() method.
  • Inside the main() method, create a for loop with 10 iterations. Inside for loop, create an object of Calculator class, an object of the Thread class, pass the object of Calculator class as a parameter, and invoke the start() method of the Thread object.
public class Main {
 public static void main(String[] args) {
  for(int i=0; i<10; i++){
   Thread thread = new Thread(new Calculator(i));
   thread.start();
  }
 }
}


Below is the partial output of a sample run of the above code:



  • Every Java Program has atleast one thread in Execution. When we run a program, JVM runs the execution thread that calls main() method.
  • Creating an object to the Thread class doesn't create an execution of the Thread. Or calling the run() method of the implemented Runnable interface will not create a new execution of Thread. Invoking start() method on creates a new execution thread.
  • When we call the start() method of Thread object, it creates another execution thread. Our program will have as many threads as calls to the start() method are made.
  • A Java program ends when all its threads(all non-daemon) finishes.
  • If the initial thread(the one that executes main() method) ends, the rest of threads continue with their execution until they finish.
  • If a thread is exited by calling System.exit(), all threads end their execution.


References:
  • http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/package-summary.html
  • http://docs.oracle.com/javase/7/docs/technotes/guides/concurrency/
  • Java 7 Concurrency Book by Javier Fernández