Square CSS

Showing posts with label java multithreading. Show all posts
Showing posts with label java multithreading. Show all posts

Sunday, November 25, 2018

Java Multithreading : ExecutorService (Real-Life Example)

In this lesson, we will see how we can use the executor service in a real-life scenario. We will use the worker threads to execute a task and thus reduce the processing time by using a thread pool.


Scenario:


Suppose you have to send emails to all the students of a college with their details.
Let's take some assumptions. Consider that it takes around 30 milliseconds to send mail to one student. Let the number of students be 1000. Considering in mind all these total time for sending mail becomes time multiplied with students count plus some delta time for processing extra code.

Assumptions:


The total number of students: 1000 students.
The time it takes to send mail for one student=30 milliseconds or 0.03 second.
Total time using single thread= 0.03 X 1000 + delta time for processing=30 seconds + delta time for processing.

Using Single Thread:


Let's create a single thread using newSingleThreadExecutor() method of ExecutorService. Create a thread which takes 30 milliseconds to execute its task.

  


class SendMail implements Runnable {
      public void run() {
              try{
                   Thread.sleep(30);
              } catch (InterruptedException e) {
                   e.printStackTrace();
              }
      }
}


Run the task for 3000 times. For running with single thread the code will be like below.
  


ExecutorService es=Executors.newSingleThreadExecutor();for(int i=0;i<3000;i++){
     es.submit(new SendMail());
}


We can print the date to find the time difference between start and end of the code to send mail.


It almost came out 30 seconds + some delta time due to processing.

Using Thread Pool:


Let's create a single thread using newFixedThreadPool(threadCount) method of ExecutorService. Create a thread which takes 30 milliseconds to execute its task.

  


class SendMail implements Runnable {
      public void run() {
              try{
                   Thread.sleep(30);
              } catch (InterruptedException e) {
                   e.printStackTrace();
              }
      }
}


Run the task for 3000 times. For running with a thread pool of 10 worker threads, the code will be like below.
  


ExecutorService es=Executors.newFixedThreadPool(10);
for(int i=0;i<3000;i++){
     es.submit(new SendMail());
}


We can print the date to find the time difference between start and end of the code to send mail.


It almost came out 3 seconds using 10 worker threads due to processing.

Conclusion:


When a single thread is used to execute task it took more than 30 seconds. We created a thread pool of 10 worker threads, then it took almost 3 seconds. So we can create multiple threads using executor service and can reduce the time and increase the efficiency of a task in the project which requires a similar task to be done multiple times.

Refer the video tutorial:


Saturday, November 17, 2018

Java Multithreading : Volatile Key (Basic Synchronization)

The concepts of the volatile key are often misunderstood and often explained in the wrong way.
Providing the concepts in simple and in an easy to understand way.

What is volatile Key?


Volatile is a keyword which can be applied to a variable to perform basic synchronization.
To make a variable volatile provide volatile in the declaration of the variable.

Uses of volatile key:

  • Used to make operation on a variable like reading and writing through main memory.
  • It acts as the operations are performed in a synchronized block.
  • The value of a variable will never be caught locally.

Example :


To make use of volatile keyword just provide in the declaration only.
Below is the example where int data variable is used along with the volatile keyword.
      


public class MyVolatile {

      private volatile int data = 0; 
 
      /* other codes along with                    

       getter & setter */

}



Refer the video tutorial :






                    Executor Service is an interface in Java to create a pool of the ... 

Friday, November 16, 2018

Java Multithreading : Synchronization (Method Level)

In multithreading, synchronization is used to allow only one thread at a time to access the shared resource.

Uses of Synchronization keyword in Java :

  • To prevent the other thread to interface with the current thread execution.
  • To maintain consistency where multiple threads are accessing the same resource.

Synchronization can be applied in three ways :

  • Method level synchronization
  • Synchronization block
  • Static Synchronization

Method Level Synchronization :


In method level synchronization the method is marked with synchronization keyword.
In this case, the lock is acquired on the object. The lock is released when the execution of the synchronization method is completed.

Example of method level Synchronization :


Below is the program in which inc() method is called simultaneously by the two threads t1 and t2.
The inc method is incrementing the count by 1. The count ++ is being performed in the inc() method. The count++ is nothing but count = count+1. If this process is performed without synchronized keyword then the count is not coming 10000 but it is coming less than that.



Why this is happening?


Here inc() method is performing count++ or in other terms count=count+1. 
Suppose for one thread t1 (let) count be 355 suddenly thread t2 also entered inc() method at the same time t2 also read count as 355 only. At this moment t1 performed count=355+1 and t2 also did the same. The result after inc() method execution for t1 and t2 at this step will be count=356 only. 
But if t1 would have executed first then count would have been 356 and t2 when tried to execute then it would have come out with the result of count as 357.

Let's apply the Synchronized key.



Using the synchronized key on method level the result came correct as 10000.


Refer the video tutorial :





                    The concepts of the volatile key are often misunderstood and often ... 

Monday, October 29, 2018

Java Multithreading : Introduction

Multithreading refers to the process of executing multiple threads simultaneously.
A thread can be considered as a smaller unit of processing.
Both multithreading and multiprocessing can be used to achieve multitasking. But in multithreading, threads use shared memory and context switching takes very less time.
Multithreading is mostly used in applications related to games and animations.

Advantages of Multithreading :


  • If any exception occurs in a thread then it doesn't block the other threads or tasks from execution.
  • Multiple tasks can be executed in parallel so it saves time.
  • It doesn't block the user to wait for a particular task to complete as threads are independent of each other.


                    In Java we can create a thread in two ways... 

Some Algorithms

Algorithm: Tower of Hanoi

Tower of Hanoi consists of three towers called as pegs with n number of rings. Rings are of different size.  Conditions to be fulfill...

Popular Posts