Learn about concurrency in java

0
2625

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.
  2. 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: –

      Here we have a new type of thread MyThread.

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

      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:

      thread

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


      Output :

    • 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.

      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

  3. 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
  4. 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

  5. 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.
  6. 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.
  7. 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.


Output :

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.


Output :

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