Monday, April 29, 2013

Java Concurrency Part 1

Hi i will try to give back some of the knowledge I've learned through the years by reading blogs, so I'm going to start with a series of articles in which I will explain to you the java concurrency API, I hope you can learn something from it, as I did.

PART I - INTRODUCTION

What is a thread?

The term concurrency means tasks executing simultaneously, java supports concurrency via threads objects. A thread is a task of execution in a program. The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.

There are 2 types of threads in java, daemon and non-daemon, when the JVM starts up, there is usually a single non-daemon thread and is the one that calls the main() method of a program, and the JVM executes until a call to System.exit() has been made or all threads that are not daemon threads have died.

Making it easier to understand daemon threads can be called System threads and non-daemon threads can be called program or user threads, and an applications runs until there are not program threads, to execute.

There are two ways to create a thread:

  1. Extending the Thread class and overriding the run().
      public class Calculator extends Thread {
        public void run() {
          .....
        }
      }
Implement the Runnable interface and then create a Thread object and set the Runnable object to it.

public class Calculator implements Runnable {
    public void run() {
      .....
    }


Whether the thread extends Thread class or implements the Runnable interface, either way a Thread Object has to be created to execute the thread. But creating an Object of the Thread class doesn't create a new execution thread, only calling the start() method creates a new execution thread.
  1. If thread object extends Thread: 
     Calculator calculator = new Calculator (); calculator.start();
  2. If thread object implements Runnable:
      Thread thread = new Thread(new Calculator ())
      thread.start();
Thread states

A thread has the following states:

New: The Thread object has been created, but start() has not been invoked, at this point is not consider alive.
Runnable: start() has been invoked and is eligible to run, but the schedule has not selected it.
Running: The thread is selected by the scheduler and executes the run().
Waiting/blocked/sleeping: Thread is alive but NOT ELIGIBLE TO RUN.
Dead: run() has completed.

After calling start() method the jvm does the following:
  1. A new thread of execution starts.
  2. The thread moves from new state to runnable state.
  3. When the thread gets chance to execute, its run() will execute.
A thread can be started just once, this means that a call to the start() method can not be done more than once. If start() is called more than once an IllegalThreadStateException will rise.

Running multiple threads

A thread can be identified by the following attributes.
  • ID: Unique identifier for each Thread.
  • Name: Name of Thread.
  • Priority: Threads can have a priority between one and 10, where one is the lowest priority and 10 is the highest one.
  • Status: Status of Thread. A Thread can be in one of these five states: new, runnable, blocked, waiting, or terminated.
When multiple threads run simultaneously each one gets the CPU according to the scheduler. There is not guarantee which thread will start or end first. The only guarantee is that each thread will run to completion.

 Example:
    public class Calculator extends Thread {
      public void run() {
        System.out.println(“Thread running:” + this.getName());
      }
    }
          ......
          Calculator first = new Calculator(“First”);
          first.start();
          Calculator second = new Calculator(“Second ”);
          second.start();
          ......

There is no guarantee that the order of the messages will be:
          Thread running: first
          Thread running: second
The only guarantee is that both messages will appear in console.

The join() method of the thread class suspends the execution of the calling thread until the join thread has finished.
          ...........
          Calculator first = new Calculator(“First”);
          first.start();
          try {
              first.join():
          } catch (InterruptedException e) {
              e.printStackTrace();
          }
         Calculator second = new Calculator(“Second ”);
         second.start();
         ...........

This way the console must print the message in the following order:
         Thread running: first
         Thread running: second


Go to part 2