Thursday, July 11

Effective java : Item 66 : Synchronized access to shared mutable data




                  Synchronized access to shared mutable data

What is Mutable Data? : data that can be modified.

Shared ?: Being accessed and updated by multiple threads

What is Synchronized access? :

Synchronization is a keyword used  with a method or block of code to restrict the access of shared data to only one thread at one time. Essentially it provides locking mechanism .

But , Is synchronization all about locking and restriction. NO

Another very important behavior Synchronization provides is visibility. 

What is visibility ?

When a thread makes a change to shared data  this change is not always visible to other threads working on same data If shared data is not synchronized

Let’s take an example :

Public class Climate {

Boolean stop;



Thread rain =new Thread(new Runnable (



Public void run(){



While(!stop){



Keepraining();



}



);)



Rain.start();



Stop=true;





}

Here there are two threads .
 1. Main thread
 2) rain thread spawned from main thread.  

 You may think that rain thread will execute once or twice and will stop as soon as  stop=true is executed in main thread. But this may not be the case every time , in every environment .Instead rain thread keeps working on its cached data and any change in the data does not become visible to rain thread unless it is explicitly brought in sync. 

                     So synchronization bring every participating thread in sync. To make this program run as expected every time in every environment value of stop variable should be accessed /mutated with in a synchronize block.

Write need to be synchronized for mutually exclusive access to shared data AND read needs to be synchronized so that any change in the data from any thread is visible to the thread currently reading it .

So Synchronization is important for two very strong features in multi - threaded programming


  •      Locking
  •    Visibility



 Please comment/question to discuss it further:



No comments:

Post a Comment