Synchronization in Java

When We should use Synchronization in Java and when we should not?

Questions by sathyasha   answers by sathyasha

Showing Answers 1 - 40 of 40 Answers

vaneet

  • Jun 3rd, 2008
 

Synchronization is helpful only when you know that more than 1 thread is trying to access the same method. for that purpose, you wuill have to synchronize the method ie. only that thread which has the key for the lock(the synchronization lock) will be let inside. No other thread can access that method untill it is given the key

Synchronization is useful when you have a shared  resource(say a shared variable) which is trying to be accessed by multiple threads.

Say you have two threads T1 and T2 and both want to access the variable 'a'. Now if T1 changes the value of 'a' from 1 to 2 and then T2 reads it but then T1 changes the value again now from 2 to back 1, what T2 read was a wrong value of 'a'. To avoid this, Locks are used. T1 has the lock now untill it finishes it's work with 'a' then releases the lock. T2 now will gain the lock and work on 'a'.

Uma Sundar

  • Jun 16th, 2008
 

Synchronization means several methods can be excuted simultaniously using the same object.But if you want to excute one method at a time,that method can be declared as synchronized.For example,in the stack either the push or pop operation can be executed at one time,for that you declared both methods as synchronised.

  Was this answer useful?  Yes

Synchronisation is the process of allowing only single thread to access field.In a scenario where value of field is changing there synchronisation is required to avoid inconsistencies else if field is constant then multiple threads can access that field at the same time.

  Was this answer useful?  Yes

rinumca

  • Jun 29th, 2008
 

Generally each thread will have its own resource or data to action. In this case there is no possibility for data inconsistency. Somtimes two threads may act on one resource of data and in this case data inconsistency may occur. To overcome this problem java introduces synchronization concept. In synchronization only one thread allowed to operate on the resource when a thread access a synchronized data it calls wait method, it is a indication to the thread schedulor not to allow any thread to access the same resource until the first thread job is completed. "synchronized" is a keyword which can be used to tell through method. We can make a method as synchronized and block as synchronized. We can use synchronized keyword to avoid inconsistency.

roopesh12

  • Jul 1st, 2008
 

There are two types of variables.
1. local variables
2. static or instance variables.

local valiables like method parameters are stored in stacks and instance are stored in Heap. You are not bothered to take care for any local things for synchronizations as that remains in thread's address. So two threads can never spoil the state that is in stack. So only thing that is in heap should be considered for synchronization. When you need some code to be atomic keep that in synchronized block. Like if you want to set r ,g, b colors in a method keep them in asynchronized block as the possibility is another thread will get partialy written data.

singh_ap

  • Sep 13th, 2009
 

Synchronization is used in Java, if there are multiple threads which are accessing same variable, then they access it one by one.

  Was this answer useful?  Yes

Gurumoorthy.M

  • Jul 27th, 2011
 

Synchronization is commonly used in multi-threaded program. In multi-thread program more than one thread tries to access the particular resources. But using synchronization we can able to access one by one resource. For example: Let us assume obj 1, obj 2, obj 3. if obj 1 accessing the resource means obj 2 and obj 3 does not allow to access that same resource at same time, after completing the obj 1 then it will be a chance for obj 2 and obj 3.

  Was this answer useful?  Yes

sandeep thakur

  • Sep 23rd, 2011
 

when multiple child thread are used in our program, in this case any child will be executed before terminate the one thread and problem will occur so in the case we used synchronization.

  Was this answer useful?  Yes

sampra

  • Mar 7th, 2012
 

Synchronization is useful when you have a shared resource(say a shared variable) which is trying to be accessed by multiple threads.

  Was this answer useful?  Yes

Arvindanathan

  • Dec 3rd, 2013
 

Code
  1. /*

  2.  * @author Arvindanathan J

  3.  */

  4. //Execute this method with synchronized  and without synchronized  block as mentioned below.Then you can understand how it works

  5. package com.syn;

  6.  

  7. class SynchronizationDemo  implements Runnable

  8. {

  9.         public static void main(String arg[])

  10.         {

  11.                 System.out.println("Main Block");

  12.  

  13.                 SynchronizationDemo sy=new SynchronizationDemo();

  14.  

  15.                 System.out.println("Thread Name : "+Thread.currentThread().getName());

  16.  

  17.                 Thread thread1= new Thread(sy);

  18.  

  19.                 thread1.setName("Test1");

  20.  

  21.                 thread1.start();

  22.  

  23.                 Thread thread2=new Thread(sy);

  24.  

  25.                 thread2.setName("Test2");

  26.  

  27.                 thread2.start();

  28.  

  29.                 Thread thread3=new Thread(sy);

  30.  

  31.                 thread3.setName("Test3");

  32.  

  33.                 thread3.start();

  34.  

  35.                 System.out.println("Thread Name : "+Thread.currentThread().getName());

  36.         }

  37.         public void run()

  38.         {

  39.  

  40.                 synchronized (SynchronizationDemo.class)//hide this line to know the differrence

  41.                 {

  42.                         System.out.println("we are entering Run Method ");

  43.  

  44.                         System.out.println("Thread Name : "+Thread.currentThread().getName());

  45.  

  46.                         try{

  47.  

  48.                                 Thread.sleep(1000);

  49.  

  50.                         }

  51.  

  52.                         catch(InterruptedException e)

  53.                         {

  54.  

  55.                                 System.out.println("Sleeping ");

  56.                         }

  57.  

  58.                         System.out.println("Run Method ends..");

  59.                 }

  60.         }

  61. }

  62.  

  63. Output with synchronized block:

  64. Main Block

  65. Thread Name : main

  66. we are entering Run Method

  67. Thread Name : Test1

  68. Thread Name : main

  69. Run Method ends..

  70. we are entering Run Method

  71. Thread Name : Test3

  72. Run Method ends..

  73. we are entering Run Method

  74. Thread Name : Test2

  75. Run Method ends..

  76. Output after hidding  synchronized line:

  77. Main Block

  78. Thread Name : main

  79. Thread Name : main

  80. we are entering Run Method

  81. Thread Name : Test1

  82. we are entering Run Method

  83. Thread Name : Test2

  84. we are entering Run Method

  85. Thread Name : Test3

  86. Run Method ends..

  87. Run Method ends..

  88. Run Method ends..

  89.  

  90.  

  91.  



  Was this answer useful?  Yes

Yeswanth

  • Dec 6th, 2013
 

If you want to allow only one thread at a time to access block of code or method then we will go for synchronization.

Code
  1. public synchronized

  2. void singleProcess() {

  3. // Insert code here

  4. }

  Was this answer useful?  Yes

In simple terms we can say only one thread can act on selected resource(method or variable).

Understanding the above sentence is as follows::
For example we are booking any ticket in a particular bus for that when we select a seat in that particular bus, so when we select any seat then it calls bookTicket() function. Here consider that two persons are there per1 and per2 both of them are trying access the same seat, then in that case to whom do we need to give that seat. Here one way is ...the person who selects required seat first will have to get that seat. Our way of thinking is correct but how can you told this to java code? simple by giving
synchronized keyword for that method as given below

public synchronized boolean bookTicket(){
//Insert some code here
}

Lets think how java is helping us to resolving our problem......synchronized is used to lock that
particular method to invoking thread i.e which ever the thread tries to access that particular method
is locked so that other threads cannot access this method till that locked thread accomplishes the
required task in that method.

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions