Java ProgrammingLearn about concurrency in java

Learn about concurrency in java

In this tutorial we will learn about concurrency, what are concurrent code, how to implement process and threads, synchronization for code blocks and methods and callable interface and features along with example.

  • To learn about concurrency in java just take a brief look on the points given below :

 

    1. Concurrent Code : It is nothing but the capability to run multiple programs or multiple parts of a program in parallel. At the language level java support to the concurrency.

 

A. Process and Threads: – In this case there are two basic units of execution processes and threads. Through an operating system feature, processing time for a single core is shared among processes and threads.

Processes: – It is nothing but the self contained execution environment. Each process has its own memory space. To support communication between processes, most of the operating systems support Inter Process Communication (i.e. IPC) resources. It is also used for communication between processes on different systems. In process a java application runs by default. Each process has its own address space, executable code and a unique process identifier. A one process can contain multiple threads. It is used for heavy weight tasks. Processes have more overheads than threads.

Threads: – Thread is similar to a program that has a single flow of control. Each flow of control may be thought of as a separate tiny program or module called as a thread. Threads are run in parallel to other threads, so does not mean that they actually run at the same time. Thread has a priority. It is also called as lightweight threads or lightweight processes. All the threads are running in the single processor, the flow of execution is shared between the threads. It shares the same address space. It allows different tasks to be performed concurrently. Context switching between threads is relatively less expensive than processes.

Figure of Process and Threads: –
thread

      • a. Creating Threads: –In java creating threads is very simple. These are implemented in the form of objects that contain a method is called as run(). The run() method is important part of any thread. It is help to makes entire body of a thread. And this is the only method, which is help to threads behavior can be implemented. The run() method should be called by an object of the concerned thread. This can be obtained by creating the thread and initiating it with the help of another thread method is known as start().
        A new thread can be created in two ways: –

i. By creating a thread class: – Define a class that extend Thread class and override its run() method with the code required by the thread.

ii. By converting a class to a thread: – Define a class that implements Runnable interface. The Runnable interface has only one method which is run(), that is to be defined in the method with the code to be executed by the thread.

      • b. Extending The Thread Class : – We can compose our class Runnable as thread by extending the class java.lang.Thread. It follows the below steps: –

        I. Declare the class as extending the Thread class.
        II. Implement the run() method that is responsible for executing the sequence of code that the thread will execute.
        III. Create a thread object and call the start() method to initiate the thread execution.

Declaring the Class: –

Class MyThread extends Thread
{
		. . . . . . . . .
		. . . . . . . . . 
}

Here we have a new type of thread MyThread.

Implementing the run() Method : –Here the run method is inherited by the class MyThread.

Public void run()
{
		. . . . . . . . . . . . . 
		//Thread code
}

If you start the new thread, Java calls the run() method which is threads, in this run() method all the action takes place.

Starting New Thread : – To create and run an instance of our thread class, we must write in following way:

/* Here instantiates a new object of class MyThread. In this case the thread is in a newborn state*/ 
MyThread aThread = new MyThread();

/*Here calls the start() method causing the thread is move into the runnable state. Then the Java runtime will schedule the thread to run by calling its run() method. At this time thread is to be in the running state.*/
aThread.start(); //calls run() method

thread

Example : This example shows how to create threads using the thread class in java.

class c1 extends Thread//here extends Thread
{
		public void run()//define run() method
		{
			for (int i=1;i<=4;i++)//check condition
			{
				System.out.println("\t From Thread C1: i= "+i);
			}
			System.out.println("Exit form C1");
			}
}
class C2 extends Thread//here extends Thread
{
			public void run()//define run() method
			{	
			for (int j=1;j<=4;j++) //check condition
			{
				System.out.println("\t From Thread C2: j= "+j);
			}
			System.out.println("Exit from C2");
		}
}
class c3 extends Thread//here extends Thread
{
		public void run()//define run() method
		{
			for(int k=1;k<=4;k++)//check condition
			{
				System.out.println("\t From Thread c3: k= "+k);
			}
			System.out.println("Exit from C3");
		}
}
class ThreadMain //main() method
{
			public static void main(String[] args) 
			{
				new c1().start();//call c1
				new C2().start();//call c2
				new c3().start();//call c3
			}
}

Output :

From Thread C1: i= 1
			From Thread C1: i= 2
			From Thread C1: i= 3
			From Thread C1: i= 4
Exit form C1
	 		From Thread C2: j= 1
		 	From Thread C2: j= 2
		 	From Thread C2: j= 3
	 		From Thread C2: j= 4
Exit from C2
			From Thread c3: k= 1
			From Thread c3: k= 2
			From Thread c3: k= 3
			From Thread c3: k= 4
Exit from C3

 

      • c. Stopping and Blocking a Thread : –

i. Stopping a Thread : – If we want to stop a thread from running further, then we may so by invoking its stop() method.

aThread.stop();

This method is causes the thread to move to the dead state. A thread will also move to the dead state automatically when it reaches the end of its method. This method used when premature death of a thread is desired.

ii. Blocking a Thread : – It is nothing but the thread can also be temporarily blocked or suspended from entering into the runnable and after running state by using one of the below method : –
I. sleep() : – Blocked for a specified time.
II. suspend() : – Blocked as far as further orders.
III. wait() : – Blocked as far as certain condition occurs.
These methods are responsible for the thread to go into the blocked state. The thread will return to the runnable state when the defined time is expire in the sleep() method, the resume() method is called in the suspend() method and the notify() method is invoked in the wait() method.

      • d. Life Cycle of a Thread : – During a life time of a thread, thread is always in one of the five states which are below: –

1. Newborn State : – It is nothing but the when create a thread object, the thread is born and this is called as newborn state. The thread is not still schedule for running. In this situation we can do only one of the following things: –
a. Schedule it for running using start() method.
b. Kill it using stop() method.
If thread scheduled, it moves to the runnable state.

Newborn State

    1. Runnable State : – It means that the thread is ready for execution and is waiting for the availability of the processor, i.e. the thread is entered the queue of threads that are waiting for execution. If all threads have equal priority, then they are given time slots for execution in round robin fashion, i.e. first-come, first-serve form. If we want a thread to relinquish control to another thread to equal priority before its turn comes, we can do this with the help of yield() method.
      yield

 

    1. Running State : – It is nothing but the processor has given its time to the thread for execution. The thread runs before it relinquishes control on its own or it is preempted by a higher priority thread. Below situations for relinquish its control: –

 

      • a. It has been suspended using suspend() method. A suspended thread can be refreshed by using the resume() method. This is useful when we do not want to kill a thread, but we want to suspend a thread for some time due to some reason.

suspend

      • b. It has been made to sleep. Using a sleep(time) method, we can put a thread to sleep for a defined time period. Time is in milliseconds. It means that thread is out of the queue during specified time period. When time period is expired then the thread re-entered into runnable state.

sleep

      • c. It is used for told to wait a thread until some event occurs. This is done using wait() method. Using notify() method the thread can be scheduled to run again.

wait method

 

    1. Blocked State : – When a thread is prevented from entering into the runnable state and after the running state, then a thread is in a blocked state. This arises when the thread is suspended, sleeping, or waiting state in order to satisfy certain conditions. This blocked thread is considered not runnable but not dead, so this thread is fully qualified to run again.

 

    1. Dead State : – When a thread has completed executing its run() method, that means it end its life. It is a natural death. We can kill thread by sending stop message, at any state, when it is born, or while it is running, or even when it is in not runnable state.

8

b. Synchronization for code blocks and methods : –

Synchronization for code blocks : – A synchronized block can be used for avoid race conditions. On any particular resource of the method to perform synchronization synchronized block can be used. It is used to lock an object for any shared resource. The scope of block is smaller than the synchronized method. This block is defined with synchronized keyword. This is useful for generally reduce scope of lock. This block provides granular control over lock. Java.lang.NullPointerException exception can throw synchronized block. In this case thread acquires lock when they enter into synchronized block and release when they leaves synchronized block. In this case only one thread can execute the synchronized block at a time. Compare to synchronized method less performance hit.

Synchronization for code methods : – This keyword is applied to only methods, not on classes and not on variables. In this case synchronized keyword indicates that a method can be accessed by only one thread at a time. It is used for put lock on the current instance. That means containing a synchronized block we can replace a synchronized method with a non-synchronized method. In java synchronized method is very slow and can less in performance. This method always locks either on current object represented by this keyword or class level lock. Scope of the lock will be throughout the method scope. This synchronized method is more expensive than synchronized block in the performance.

Example : This example shows how to use synchronized blocks and methods in java class.

class SynchroTable 
{ 
	void displayTable(int num)//define method
	 {  
	   synchronized(this)
	   {//synchronized block  
	     for(int i=1;i<=4;i++)//check condition
	     {  
	      System.out.println(num*i);
	      try
	      {  //sleep a thread in defined time period
	       Thread.sleep(1400);  
	      }
	      catch(Exception ex)
	      {
	    	  System.out.println(ex);
	      }  
	     }  
	   }  
	 }//end of the method  
	}  
	  
	class MyThread1 extends Thread//class1 extends Thread
	{  
		SynchroTable t;//create object of class
	MyThread1(SynchroTable t)//create constructor of MyThread1
	{  
	this.t=t;//this refers to t
	}  
	public void run()//define method run()
	{  
	t.displayTable(4); ////print table of 4 
	}  
	  
	}  
	class MyThread2 extends Thread//class2 extends Thread
	{  
		SynchroTable t;  
	MyThread2(SynchroTable t)//create constructor of MyThread2
	{  
	this.t=t;//this refers to t
	}  
	public void run()//define method
	{  
	t.displayTable(30); //print table of 30
	}  
	}  
	 
	class Test
	{  
	public static void main(String args[])//main method
	{  
		SynchroTable obj = new SynchroTable();//only one object  
		MyThread1 mt1=new MyThread1(obj);  //create object of MyThread1
		MyThread2 mt2=new MyThread2(obj);  //create object of MyThread2
		mt1.start();  //call MyThread1
		mt2.start();  //call MyThread2
	}  
	}  

Output :

4
8
12
16
30
60
90
120

 

c. Callable interface and futures: –

Callable interface and Futures : – This is similar to Runnable interface. It ii designed for classes whose objects are probably executed by another thread. It need to implement call() method. It can return a value. It can throw checked exception. Future is used for future.

Example : This example shows how to use callable interface future and executor service in java class.

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class CallableEx 
{
	public static void main(String args[]) throws InterruptedException,ExecutionException 
		{
		//es object submit the callables within fixed size thread pool 10
		ExecutorService es = Executors.newFixedThreadPool(10);
		ThreadClass t1 = new ThreadClass();//create object of Thread1
		// 5 threads executing the task
		for (int i = 0; i <= 5; i++) 
		{
			//future is used for store the return type 
			Future<String> future = es.submit(t1);
			System.out.println(future.get());
		}
	}
}
//Creating threads  implementing {Callable}
class ThreadClass implements Callable<String> //
{
	//override call method to create thread name
	public String call() throws Exception
	{	
		//return current thread name
		return Thread.currentThread().getName();
	}
}

Output :

pool-1-thread-1
pool-1-thread-2
pool-1-thread-3
pool-1-thread-4
pool-1-thread-5
pool-1-thread-6

Thus, in this tutorial we learnt about what are concurrent code, how to implement process and threads, synchronization for code blocks and methods and callable interface and futures with example.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -