Home Java Thread Synchronized Threads

Related Tutorials


 
 

Share on Google+Share on Google+

Synchronized Threads

Advertisement
In Java, the threads are executed independently to each other. These types of threads are called as asynchronous threads.

Synchronized Threads

     

In Java, the threads are executed independently to each other. These types of threads are called as asynchronous threads. But there are two problems may be occur with asynchronous threads.

  • Two or more threads share the same resource (variable or method) while only one of them can access the resource at one time.
  • If the producer and the consumer are sharing the same kind of data in a program then either producer may produce the data faster or consumer may retrieve an order of data and process it without its existing. 

Suppose, we have created two methods as increment( ) and decrement( ). which increases or decreases value of the variable "count"  by 1 respectively shown as:

public void increment( ) {
  count++;
  }

  public void decrement( ) {
  count--;
  }
public int value() {
        return count;
    }

When the two threads are executed to access these methods (one for increment( ),another for decrement( )) then both will share the variable "count". in that case, we can't be sure that what value will be returned of variable "count". 
We can see this problem in the diagram shown below:

To avoid this problem, Java uses monitor also known as ?semaphore? to prevent data from being corrupted by multiple threads by a keyword synchronized to synchronize them and intercommunicate to each other. It is basically a mechanism which allows two or more threads to share all the available resources in a sequential manner. Java's synchronized is used to ensure that only one thread is in a critical region. critical region is a lock area where only one thread is run (or lock) at a time. Once the thread is in its critical section, no other thread can enter to that critical region. In that case, another thread will has to wait until the current thread leaves its critical section.

General form of the synchronized statement is as:

synchronized(object) { 

// statements to be synchronized 

}

Lock:

 Lock term refers to the access granted to a particular thread that can access the shared resources. At any given time, only one thread can hold the lock and thereby have access to the shared resource. Every object in Java has build-in lock that only comes in action when the object has synchronized method code. By associating a shared resource with a Java object and its lock, the object can act as a guard, ensuring synchronized access to the resource. Only one thread at a time can access the shared resource guarded by the object lock.
  
Since there is one lock per object, if one thread has acquired the lock, no other thread can acquire the lock until the lock is not released by first thread. Acquire the lock means the thread currently in synchronized method and released the lock means exits the synchronized method. 
Remember the following points related to lock and synchronization:

  • Only methods (or blocks) can be synchronized, Classes and variable cannot be synchronized.
     
  • Each object has just one lock.
      
  • All methods in a class need not to be synchronized. A class can have both synchronized and non-synchronized methods.
     
  • If two threads wants to execute a synchronized method in a class, and both threads are using the same instance of the class to invoke the method then only one thread can execute the method at a time.
     
  • If a class has both synchronized and non-synchronized methods, multiple threads can still access the class's non-synchronized methods. If you have methods that don't access the data you're trying to protect, then you don't need to synchronize them. Synchronization can cause a hit in some cases (or even deadlock if used incorrectly), so you should be careful not to overuse it.
      
  • If a thread goes to sleep, it holds any locks it has?it doesn't release them.
      
  • A thread can acquire more than one lock. For example, a thread can enter a synchronized method, thus acquiring a lock, and then immediately invoke a synchronized method on a different object, thus acquiring that lock as well. As the stack unwinds, locks are released again.
     
  • You can synchronize a block of code rather than a method.
     
  • Constructors cannot be synchronized

There are two ways to synchronized the execution of code:

  1. Synchronized Methods
     
  2. Synchronized Blocks (Statements)

Synchronized Methods: 

Any method is specified with the keyword synchronized  is only executed by one thread at a time. If any thread want to execute the synchronized method, firstly it has to obtain the objects lock.  If the lock is already held by another thread, then calling thread has to wait.  
Synchronized methods are useful in those situations where methods are executed concurrently, so that these can be intercommunicate manipulate the state of an object in ways that can corrupt the state if . Stack implementations usually define the two operations push and pop of elements as synchronized, that?s why pushing and popping are mutually exclusive operations. For Example if several threads were sharing a stack, if one thread is popping the element on the stack then another thread would not be able to pushing the element on the stack.
 

The following program demonstrates the synchronized method:

 

class Share extends Thread{
  static String msg[]={"This""is""a""synchronized""variable"};
  Share(String threadname){
  super(threadname);
  }
  public void run(){
  display(getName());
  }
  public synchronized void display(String threadN){
  for(int i=0;i<=4;i++)
  System.out.println(threadN+msg[i]);
  try{
  this.sleep(1000);
  }catch(Exception e){}
  }
}
public class SynThread1 {
  public static void main(String[] args) {
  Share t1=new Share("Thread One: ");
  t1.start();
  Share t2=new Share("Thread Two: ");
  t2.start();
}
}

Output of the program is:

C:\nisha>javac SynThread.java

C:\nisha>java SynThread
Thread One: This
Thread One: is
Thread One: a
Thread One: synchronized
Thread One: variable
Thread Two: This
Thread Two: is
Thread two: a
Thread Two: synchronized
Thread Two: variable

In this program, the method "display( )" is synchronized that will be shared by both thread's objects at the time of program execution. Thus only one thread can access that method and process it until all statements of the method are executed. 

Download this Program

Synchronized Blocks (Statements)

Another way of  handling synchronization is Synchronized Blocks (Statements). Synchronized statements must specify the object that provides the native lock. The synchronized block allows execution of arbitrary code to be synchronized on the lock of an arbitrary object.

General form of synchronized block is:

synchronized (object reference expression)
   {
// statements to be synchronized 
}

The following program demonstrates the synchronized block that shows the same output as the output of the previous example:

 

class Share extends Thread{
  static String msg[]={"This""is""a""synchronized""variable"};
  Share(String threadname){
  super(threadname);
  }
  public void run(){
  display(getName());
  }
  public void display(String threadN){

   synchronized(this){
  for(int i=0;i<=4;i++)
  System.out.println(threadN+msg[i]);
  try{
  this.sleep(1000);
  }catch(Exception e){}
  }
}
public class SynStatement {
  public static void main(String[] args) {
  Share t1=new Share("Thread One: ");
  t1.start();
  Share t2=new Share("Thread Two: ");
  t2.start();
}
}

Output of the Program

 C:\nisha>javac SynStatement.java

C:\nisha>java SynStatement
Thread One: This
Thread One: is
Thread One: a
Thread One: synchronized
Thread One: variable
Thread Two: This
Thread Two: is
Thread Two: a
Thread Two: synchronized
Thread Two: variable

Download this Program

Advertisement

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: December 15, 2008

Related Tutorials

Discuss: Synchronized Threads   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:13
CD
February 15, 2012
Output Not as mentioned

I am not sure whether the above example (with synchronization block) have been executed or not. But, I tried executing them. First thing, it does not compile because of missing braces. Once i fixed that issue, it does not give desired result as posted, instead it prints randomly every time you execute but definitely not gives single time the posted output. And i think that was not the objective of this article. The last output that i got, am pasting it here: Thread One: This Thread Two: This Thread One: is Thread Two: is Thread One: a Thread Two: a Thread Two: synchronized Thread One: synchronized Thread One: variable Thread Two: variable Hope the author reads my post and post corrections.
balaraju
March 1, 2012
about java

briefly gives the matter
Sushant
April 16, 2012
Threading

In the above example "public void display(String threadN)", why threadN is passed to display? What is the use of that?
Raveesh Kumar
April 28, 2012
java

This program is not synchronized
Andy
May 9, 2012
sync thread examples

Tried running your provided code and neither examples produced syncd output. Besides, there is a bug in the second example. One curly bracket is missing. Thread One: This Thread One: is Thread One: a Thread Two: This Thread Two: is Thread Two: a Thread Two: synchronized Thread Two: variable Thread One: synchronized Thread One: variable
venkataraman
June 29, 2012
venkataraman

good
Seshadri Rangaswami
December 17, 2012
Java monitor is not a "semaphore"

Java monitor is a "mutex" and not a "semaphore". Of course, mutex is a degenerated version of Semphore with only one lock.
ankur
November 1, 2012
syncronized thread

imp
Andrei
April 17, 2013
Wrong use of synchronize

Your display() method should also be static in order for the synchronized keyword to make any difference. Also I would suggest this code for a better understanding of the synchronized keyword : class Shared { public String msg[]={"This", "is", "a", "synchronized", "variable"}; public synchronized void display(String threadN){ for(int i=0;i<=4;i++){ System.out.println(threadN+msg[i]); try{ Thread.currentThread().sleep(1000); }catch(Exception e){ System.out.println("ERROR !"); } } } } class ShareThread extends Thread{ private Shared shared; ShareThread(String threadname, Shared shared){ super(threadname); this.shared = shared; } public void run(){ shared.display(getName()); } } public class NewClass { public static void main(String[] args) { Shared shared = new Shared(); ShareThread t1=new ShareThread("Thread One: ",shared); t1.start(); ShareThread t2=new ShareThread("Thread Two: ",shared); t2.start(); } }
DMCA.com