Saturday, June 10, 2017

Scenarios where Synchronized can get tricky

Everyone knows advantage of using synchronized keyword in java that they help in concurrency and atomicity but there are some scenarios where synchronized can get tricky.

Example 
package com.java5;

/* Ground rule - Access to static field should be done using static Synchronized method
 *         Access to non-static field should be done using non-static Synchronized method
*/
public class StaticNonStaticSynchronzied {

     /*************** Scenario 1*******************/
     /* Here static synchronized and non static synchronized won't block each other */
    
     static int b;
    
     /* Multiple threads can invoke staticMethod() and nonStaticMethod() simultaneously changing b value*/
    
     /* Thread 1 invoking using class object*/
     synchronized static void staticMethod(){
          b++;
     }
    
     /* Thread 2 invoking using this object*/
     synchronized  void nonStaticMethod(){
          b++;
     }
    
     /********************** Scenario 2******************/
     static int c;
    
     /*Multiple threads might invoke below method using different locks and accessing same static field*/
     synchronized  void nonStaticMethod1(){
          c++;
     }
}

Ground Rule

Ideally access to static field should be done and in scope within static synchronized method and access to non-static field should be done and in scope within non-static synchronized method

Put your comments below what do you think of these scenarios and how can you prevent it. STAY LEARNING

No comments:

Post a Comment