Java Programing laungage

Core Java Tutorial

Introduction of Core Java

How To Install JDk and Set of Path

Syntax of java Program

Difference between Java and C/C++

Advantage and Disadvantage of Java

What is Java

Why Java is not Pure Object Oriented Language

Java has Following Features/Characteristics

Limitation of Java Language and Java Internet

Common Misconception about Java

Simple Program of Java

Integrated Development Environment in java

Compile and Run Java Program

Applet and Comments in Java

Tokens in Java

Keywords in Java

Identifier and Variables in Java

Literals/Constants

Data Type in Java

Assignments and Initialization in Java

Operators in Java

Rule of Precedence in Java

Operator on Integer and Separators in Java Programming

Java Control Flow of Statements

If and If-else Selection Statement

Nested If-else and If-else-If Selection Statement

switch case and conditional operator Selection Statement

for and while Loop

do..while and for each Loop

break and labeled break statement

continue and labeled continue statement

return Statement and exit() Method

Escape Sequence for Special Characters and Unicode Code

Constants and Block or Scope

Statement in Java

Conversions between Numeric Types in Java

Import Statement in Java

User Input in Java using Scanner Class

User Input in Java using Console Class

Array in Java

One Dimensional Array

Two Dimensional Array

Two Dimensional Array Program

Command Line Argument in Java

String args Types in Java

Uneven/Jagged array in java

Math Class Function and Constant

Math Class all Function used in a program

Enumerated Types in Java

Object Oriented Programming v/s Procedural Programming

Object Oriented Programming Concepts in Java

Introduction to Class,Object and Method in Java

Class Declaration in Java

Class & Objects in java

Encapsulation in Java

Modifiers/Visibility for a Class or Interrface or member of a Class

Polymorphism in Java

Runtime polymorphism (dynamic binding or method overriding)

adplus-dvertising
Synchronization in Java
Previous Home Next

If two or more threads are sharing common resource for example a file. One thread is reading from the file while another thread writes to the file. Both Threads try to access that shared resource. This arises Race Condition .

The thread win the race, will access to file first. This may cause read or write wrong values and may malfunction or corrupt he program. So one thread should reach one time to perform action..

Synchronization is way to achieve this condition. Key of synchronization is concept of monitor which called semaphore also. This semaphore puts lock on thread so that one thread can get access at a time to the shared resources.

Synchronization achieved in Java by two ways:

  1. Using synchronized methods
  2. Using Synchronized statements
Using Synchronized Methods

In Java all objects have their monitor. To enter the monitor we put synchronized keyword on method. of the class that accessed by multiple Threads. In following example we will see what occur if don't use synchrinization

Example

/*
 *  implementation of Synchronization
 */
package threadexample;
 
class Shared
 {
     void call(String str)
		 //method that can baccessd by multiple threads
     {
         System.out.println("["+str);
         try
         {
             Thread.sleep(500);

         }catch(InterruptedException e)
         {
             System.out.println("Interrupted");
         }
     }
 }
class Caller implements Runnable
{
    String msg;
    Shared obj;
    Thread t;
    public Caller(Shared obj1,String s )
    {
        t=new Thread(this);
        obj=obj1;
        msg=s;
        t.start();

    }
    public void run()
    {
    obj.call(msg);
    }
    }
public class implementsynchronization {
    public static void main(String[] args)
    {
        Shared shr=new Shared();
    Caller thrd1=new Caller(shr,"Hello");
    Caller thrd2=new Caller(shr,"My");
    Caller thrd3=new Caller(shr,"Friends");
    try
    {
       thrd1.t.join();
       thrd2.t.join();
       thrd3.t.join();
     }
   catch(InterruptedException e)
   {
     System.out.println("Interrupted");
   }
    }

}

Output:

run:
[Hello[Friends[My]
]
]

As we can see call method from Shared class accessed by multiple threads. Our out doesn't came as expected. Now put synchronized keyword with call method like:

synchronized void call(String str)

After using synchronized word above programm and it's out put looks like:

Example

/*
 *  implementation of Synchronization
 */

package threadexample;
 
class Shared
 {
    synchronized void call(String str)
		//method that can baccessd by multiple threads
     {
         System.out.println("["+str);
         try
         {
             Thread.sleep(500);

         }catch(InterruptedException e)
         {
             System.out.println("Interrupted");
         }
     }
 }
class Caller implements Runnable
{
    String msg;
    Shared obj;
    Thread t;
    public Caller(Shared obj1,String s )
    {
        t=new Thread(this);
        obj=obj1;
        msg=s;
        t.start();

    }
    public void run()
    {
    obj.call(msg);
    }
    }
public class implementsynchronization {
    public static void main(String[] args)
    {
        Shared shr=new Shared();
    Caller thrd1=new Caller(shr,"Hello");
    Caller thrd2=new Caller(shr,"My");
    Caller thrd3=new Caller(shr,"Friends");
    try
    {
       thrd1.t.join();
       thrd2.t.join();
       thrd3.t.join();
     }
   catch(InterruptedException e)
   {
     System.out.println("Interrupted");
   }
    }

}

Output:

[Hello]
[My]
[Friends]
Using Synchronization Statement

Synchronized method can't be used in all case such as we wants to achieve synchronization on the objects which are not designed for the multithreaded access. We can achieve synchronization by help of synchronized statement. Synchronized statement can be used as follows.

synchronized(object)
{
//statement to be synchronized
}

Example we shown for synchronized method can be modified as:

/*
 /*
 *  SUing synchronize statement
 */

package threadexample;

/**
 *
 * @author R4R
 */
class Shared
 {
     void call(String str)
		 //method that can baccessd by multiple threads
     {
         System.out.print("["+str);
         try
         {
             Thread.sleep(1000);

         }catch(InterruptedException e)
         {
             System.out.println("Interrupted");
         }
         System.out.println("]");
     }
 }
class Caller implements Runnable
{
    String msg;
    Shared obj;
    Thread t;
    public Caller(Shared obj1,String s )
    {
        t=new Thread(this);
        obj=obj1;
        msg=s;
        t.start();

    }
    public void run()
    {
        synchronized(obj){
    obj.call(msg);
        }
    }
    }
public class implementsyncstmt {
     public static void main(String[] args)
    {
        Shared shr=new Shared();
       Caller thrd1=new Caller(shr,"Hello");
       Caller thrd2=new Caller(shr,"My");
        Caller thrd3=new Caller(shr,"Friends");
    try
    {
       thrd1.t.join();
       thrd2.t.join();
       thrd3.t.join();
     }
   catch(InterruptedException e)
   {
     System.out.println("Interrupted");
   }

     }
}

Output:

[Hello]
[My]
[Friends]
Previous Home Next