Let's learn java programming language with easy steps. This Java tutorial provides you complete knowledge about java technology.

Showing posts with label MULTITHREADING. Show all posts
Showing posts with label MULTITHREADING. Show all posts

Friday, 17 November 2017

What is Synchronization in Java with Example

What is Synchronization in Java

Java synchronized keyword

In this article, We are going to learn what is synchronization in java with example one-by-one in easy way so that you can understand well.

Java synchronization concept allows only one thread at a time to access shared resources i.e multiple thread can access shared resources one-by-one. 

In other words you can say, Multiple thread cannot access shared resource at the same if there is synchronization concept in our java program.

Synchronization is also known as Thread-Safe i.e only one thread can access any shared resource at a time.


What is the use of synchronization in multithreading?

There are many usage of synchronization in multithreading.
  • To prevent concurrent access to a block of code or object by multiple thread.
  • To resolve data inconsistency problems.
  • To prevent thread interference. 

Types of Synchronization

There are two types of synchronization in java multithreading.

  1. Process Based Synchronization.
  2. Thread Based Synchronization.

Here we will discuss only thread based synchronization.

Thread Synchronization in Java with Example

There are two types of thread synchronization in java and these are...

1) Mutual Exclusive
  • Synchronized method
  • Synchronized block
  • Static Synchronization

2) Inter-Thread Communication


Where we can use synchronization in java program

Synchronization is a modifier in java and we can apply it with method or block only. We cannot apply it with class and variables.

Java synchronized keyword is used to define any method or block as synchronized method or block.


Concept of Lock in Java

Synchronization is built around an internal entity known as the monitor or lock. Each object in java is associated with a monitor which a thread can lock or unlock. Only one thread at a time may hold a lock on a monitor.

Let's understand with examples.


Problem without using synchronization 

In this example we are not going to use synchronized keyword. Output will be inconsistent because there is no use of java synchronized keyword.

class Table
{
void displayTable(int n)//without using synchronized keyword
{
for(int i = 1; i <= 5; i++)
{
System.out.println(n*i);
try
{
Thread.sleep(500);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
}

class Thread1 extends Thread
{
Table t;
Thread1(Table t)
{
this.t = t;
}
public void run()
{
t.displayTable(5);
}
}

class Thread2 extends Thread
{
Table t;
Thread2(Table t)
{
this.t = t;
}
public void run()
{
t.displayTable(100);
}
}

class Test
{
public static void main(String args[])
{
Table tt =
new Table();
Thread1 one = new Thread1(tt);
Thread2 two = new Thread2(tt);
one.start();
two.start();
}
}

Output: 5
             100
             200
             10
             300
             15
             20
             400
             500
             25

The above data are displayed with inconsistency.


Java Synchronized Method

This is simple java synchronized method example where we will use synchronized keyword with method for displaying consistent data on the console. 


class Table

{

synchronized void displayTable(int n)//with synchronized keyword

{

for(int i = 1; i <= 5; i++)

{

System.out.println(n*i);

try

{

Thread.sleep(500);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
}

class Thread1 extends Thread
{
Table t;
Thread1(Table t)
{
this.t = t;
}
public void run()
{
t.displayTable(5);
}
}

class Thread2 extends Thread
{
Table t;
Thread2(Table t)
{
this.t = t;
}
public void run()
{
t.displayTable(100);
}
}

class Test
{
public static void main(String args[])
{
Table tt = 
new Table();
Thread1 one = new Thread1(tt);
Thread2 two = new Thread2(tt);
one.start();
two.start();
}
}

Output: 5
             10
             15
             20
             25
             100
             200
             300
             400
             500

Above output with consistent data by using synchronized method in java multithreading.

Java Synchronized Block

This is simple java synchronized block. By the help of synchronized block you can perform synchronization on particular resource of method.

Let's understand java synchronized block in multithreading with simple example.


class Table
{

void displayTable(int n)

{
synchronized(this)//synchronized block in java
{

for(int i = 1; i <= 5; i++)

{

System.out.println(n*i);

try
{
Thread.sleep(500);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
}
}

class Thread1 extends Thread
{
Table t;
Thread1(Table t)
{
this.t = t;
}
public void run()
{
t.displayTable(5);
}
}

class Thread2 extends Thread
{
Table t;
Thread2(Table t)
{
this.t = t;
}
public void run()
{
t.displayTable(100);
}
}

class Test
{
public static void main(String args[])
{
Table tt = 
new Table();
Thread1 one = new Thread1(tt);
Thread2 two = new Thread2(tt);
one.start();
two.start();
}
}

Output: 5
             10
             15
             20
             25
             100
             200
             300
             400
             500

Java Static Synchronization

This is simple static synchronization example in java multithreading when you apply synchronized keyword with any static method this known as static synchronization in multithreading.


class Table

{

synchronized static void displayTable(int n)//static synchronization

{

for(int i = 1; i <= 5; i++)

{
System.out.println(n*i);
try
{
Thread.sleep(500);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
}

class Thread1 extends Thread
{
public void run()
{
Table.displayTable(5);//calling with class name
}
}

class Thread2 extends Thread
{
public void run()
{
Table.displayTable(100);//calling with class name
}
}

class Test
{
public static void main(String args[])
{
Table tt = 
new Table();
Thread1 one = new Thread1();
Thread2 two = new Thread2();
one.start();
two.start();
}
}

Here we have learned synchronization in multithreading in java with examples like java synchronized method, synchronized block in java, static synchronization in java.


Share:

Wednesday, 26 July 2017

Thread Pool In Java

Java Thread Pool

Java Thread Pool

Thread pool in java manages the pool of worker thread i.e Thread pool represents a group of worker threads that are waiting for the job and reuse many times.

Most of the executor implementations in java.util.concurrent use thread pool which consists of worker thread.

In thread pool environment, a group of fixed size thread are created.

This type of pool always has a specified numbers of thread running, if a thread is somehow terminated while it is still in use, it is automatically replaced with new thread.

Thread pool contains a queue that keeps tasks waiting to get executed and here to create a new thread pool in java we can use ThreaPoolExecutor. 

This kind of thread exists separately from the Runnable and Callable tasks it executes and it is used to execute multiple tasks.

 In java, Using worker threads minimizes the overhead due to thread creation. Here Thread object use a significant amount of memory, and in a large scale application and allocating and deallocating many thread objects creates a significant memory management overhead.


Advantage of Java Thread Pool

  • It saves time because there is no need to create a new thread.

Usage of Thread Pool In Java

  • Java Thread pool mostly used in Servlet and JSP where container creates a Thread pool.

Java Thread Pool Example

Let's take look of simple example of java thread pool by using ExecutorService and Executors.

//WorkerThread.java

public class WorkerThread implements Runnable
{
private String command;
public WorkerThread(String s)
{
this.command = s;
}
public void run()
{
System.out.println(Thread.currentThread().getName()+"start.command = "+command);
processCommand();
System.out.println(Thread.currentThread().getName()+" End. ");
}
private void processCommand()
{
try
{
Thread.sleep(5000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}

public String toString()
{
return this.command;
}
}




Java ExecutorService Example

This is the test program class ThreadPoolExample.java where we are creating fixed thread pool from Executors Framework.

//ThreadPoolExample.java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPoolExample
{
public static void main(String args[])
{
ExecutorService executor = Executors.newFixedThreadPool(5);
for(int i = 0; i<10; i++)
{
Runnable worker = new WorkerThread("" +i);
executor.execute(worker);
}
executor.shutdown();
while(!executor.isTerminated())
{
}
System.out.println("finished all thread");
}
}

output : pool 1 -1- thread-1 start.command = 0
              pool 1 -1- thread-2 start.command = 1
              pool 1 -1- thread-5 start.command = 4
              pool 1 -1- thread-4 start.command = 3
              pool 1 -1- thread-3 start.command = 2
              pool 1 -1- thread-1 End.
              pool 1 -1- thread-2 End.
              pool 1 -1- thread-2 start.command = 1
              pool 1 -1- thread-5 start.command = 6
              pool 1 -1- thread-5 End.
              pool 1 -1- thread-4 End.
              pool 1 -1- thread-5 start.command = 7
              pool 1 -1- thread-4 start.command = 8
              pool 1 -1- thread-3 End.
              pool 1 -1- thread-3 start.command = 9
              pool 1 -1- thread-2 End.
              pool 1 -1- thread-1 End.
              pool 1 -1- thread-5 End.
              pool 1 -1- thread-4 End.
              pool 1 -1- thread-3 End.
              finished all thread

In the above example, There are fixed size thread pool of 5 workers threads and then we submitting 10 jobs to this pool. Since the thread pool size is 5, it will start working on 5 jobs and other jobs will be in the wait state and as soon as one of the jobs is finished, another job from the wait queue will be picked up by the worker thread and get's executed.

Share:

Facebook Page Likes

Follow javatutorial95 on twitter

Popular Posts

Link

Translate