Klaus
Klaus

Reputation: 1731

What is happening within this synchronized block

I tried to see if the variable values can be modified by multiple threads before the synchronized block. I am confused with the behavior of the below code. I created a method having a synchronized block like below

public void testMethod( String x )
{
    String myX = x.toUpperCase();
    System.out.println( myX ); // Prints the value before the critical section
    synchronized( this )
    {
        try
        {
            Thread.sleep( 5000 );
        }
        catch( InterruptedException e )
        {
            e.printStackTrace();
        }
        System.out.println( myX ); // Prints the value inside the critical section
    }
}

And then, I created two threads that call this method with two different String values like below,

Thread myThreadOne = new Thread( () -> testMethod( "T1" ) );
Thread myThreadTwo = new Thread( () -> testMethod( "T2" ) );

And called within the main method.

public static void main( String[] args )
{
    Test t1 = new Test();
    t1.myThreadOne.start();
    t1.myThreadTwo.start();
}

Now the output I was expecting was something like T1,T2,T2,T2. Or whichever thread starts last should print the value before and inside the synchronized block because it is very clear that the variable myX will have the updated value from the second thread while the first thread is sleeping or while the first thread is inside the critical section.

But the output is always the first thread value followed by second thread value. Like T1,T2,T1,T2. How come this happened? Varibale myX is outside the synchronized block, isn't the second thread modify this value. Or is it something wrong with my sample code??

Upvotes: 2

Views: 46

Answers (2)

Lazycoder-007
Lazycoder-007

Reputation: 1215

You ned to declare the myx variable outside the method :

String myX;

    public void testMethod( String x )
    {
        myX = x.toUpperCase();
        System.out.println( myX ); // Prints the value before the critical section
        synchronized( this )
        {
            try
            {
                Thread.sleep( 5000 );
            }
            catch( InterruptedException e )
            {
                e.printStackTrace();
            }
            System.out.println( myX ); // Prints the value inside the critical section
        }
    }

This will give you your desired results.

WHY :

  • Local variables are thread safe in nature and are not shared by threads
  • While the class variables are shared

You can have a look at this : Why are local variables thread safe in Java

Upvotes: 2

denniz crypto
denniz crypto

Reputation: 471

String myX is a local variable meaning that when each thread executes testMethod(string x) it will create a unique copy which is not visible to any other thread.

if you want a change in myX i would recommend using a global variable.

Upvotes: 1

Related Questions