Thursday, May 9, 2024
HomeJavaCan threads execute totally different synchronized strategies on identical object? - Java...

Can threads execute totally different synchronized strategies on identical object? – Java Code Geeks


In our earlier publish, we learnt that when a way is synchronized just one thread shall be allowed to enter the strategy. On this publish, let’s perform a little little bit of deep dive – What would occur if an object has two synchronized strategies? When a thread is executing the primary synchronized technique, will one other thread be allowed to execute the second synchronized technique? 


Video: To see the visible walk-through of this publish, click on beneath:


A number of synchronized strategies in a identical object instance

 To facilitate our examine, I’ve put-together an attention-grabbing program. On this program, we try to simulate two threads making an attempt to execute two synchronized strategies of the identical object, on the identical time limit.

01: public class GirlFriend {

02: 

03:    public void sing() {

04:       

05:       attempt {         

06:           for(int i = 1; i <= 10; ++i) {

07:                System.out.println("lullaby");

08:                Thread.sleep(100);

09:          }

10:       } catch (Exception e) {         

11:       }

12:    }

13:    

14:    public void rely() {

15:       

16:       attempt {

17:           for(int i = 1; i <= 10; ++i) {

18:                System.out.println(i);

19:                Thread.sleep(100);

20:          }

21:       } catch (Exception e) {         

22:       }

23:    }   

24: }

 This program has a ‘GirlFriend’ class. It accommodates two synchronized strategies: 

 1. ‘sing()’ declared in line #3 which prints ‘lullaby’ 10 occasions.

 2. ‘rely()’ declared in line #14 which prints ‘1’ to ’10’.

 Now we have put the thread to sleep for 100 milliseconds after printing in line #8 and #19, in order that we will seize thread dumps throughout this system execution, which is required for our dialogue.

01: public class SameObjectSynchDemo {

02: 

03:    non-public static GirlFriend girlFriend = new GirlFriend();

04:    

05:    non-public static class BoyFriend1 extends Thread {

06:       

07:       @Override

08:       public void run() {

09:          

10:          girlFriend.sing();

11:       }

12:    }

13:    

14:    non-public static class BoyFriend2 extends Thread {

15:       

16:       @Override

17:       public void run() {

18:          

19:          girlFriend.rely();

20:       }

21:    }

22:    

23:    public static void major(String args[]) {

24:       

25:       new BoyFriend1().begin();

26:       new BoyFriend2().begin();

27:    }

28: }

This SameObjectSynchDemo class accommodates two threads:

a. ‘BoyFriend1’ thread which invokes ‘GirlFriend’ object’s ‘sing()’ technique in line #10

b. ‘BoyFriend2’ thread which invokes ‘GirlFriend’ object’s ‘rely()’ technique in line #19

Each of those threads are launched concurrently in line #25, #26.

Synchronized strategies execution output

 After we executed the above program, we obtained following as output:

lullaby

1

lullaby

2

lullaby

3

lullaby

4

lullaby

5

lullaby

6

lullaby

7

lullaby

8

lullaby

9

lullaby

10

Fig: Output when sing() and rely() will not be synchronized

You’ll be able to see that the ‘GirlFriend’ object is singing and counting on the identical time i.e. you may discover that ‘lullaby’ and numbers are blended up and printed. If you will ask the ‘GirlFriend’ object to sing and rely on the identical time, it’s going to be fairly complicated. We have to assist her. That is the place the synchronized technique comes to assist. 

Now, we made each ‘sing()’ and ‘rely()’ as synchronized strategies i.e., we launched the ‘synchronized’ key phrase in line #3 and line #14 of the ‘GirlFriend’ class. After we executed this modified program, we obtained following as output:

lullaby

lullaby

lullaby

lullaby

lullaby

lullaby

lullaby

lullaby

lullaby

lullaby

1

2

3

4

5

6

7

8

9

10

Fig: Output when sing() and rely() is synchronized

You’ll be able to clearly see the distinction within the output. When each ‘sing()’ and ‘rely()’ are synchronized, ‘GirlFriend’ object first accomplished her singing after which solely began counting i.e. ‘lullaby’ was printed first after which ‘1’ to ’10’ was printed later. This could make the ‘GirlFriend’ object actually glad. This magic is just taking place due to synchronization. 

How do two Synchronized strategies work in Java?

When a thread executes the synchronized technique, it obtains the lock of the underlying object. Just one thread can maintain the lock of an object at any given time. Since ‘BoyFriend1’ thread began first, when it entered the ‘sing()’ technique, it acquired lock of the ‘GirlFriend’ object; when ‘BoyFriend2’ thread tries to enter the ‘rely()’ technique, it will attempt to purchase the lock of the identical ‘GirlFriend’ object. Since ‘BoyFriend1’ thread is already holding on to the GirlFriend’s lock, ‘BoyFriend2’ thread is not going to be allowed to accumulate the lock and will probably be put to BLOCKED state. Solely after the ‘BoyFriend1’ thread exits the ‘sing()’ technique, it would launch the GirlFriend’s lock. Solely after that ‘BoyFriend2’ thread can enter the ‘rely()’ technique.

Threads habits of Synchronized strategies

To substantiate this concept, we executed the above program and captured thread dump utilizing open-source script yCrash. We analyzed the thread dump utilizing the fastThread instrument. Right here is the generated thread dump evaluation report of this easy program. Under is the excerpt from the thread dump evaluation report:

Fig: fastThread instrument reporting 1 thread is in BLOCKED state
Fig: Transitive graph exhibiting ‘BoyFriend2’ blocked by ‘BoyFriend1’ (generated by fastThread)

Every time threads are blocked, the fastThread instrument will report them as a transitive graph. From the graph you may discover that ‘BoyFriend2’ is being blocked by ‘BoyFriend1’. (Word: This graph would make extra sense particularly when a number of threads are getting blocked. You’ll be able to take a look at the introductory publish the place a number of threads obtained BLOCKED). When clicking on the thread names you may see its full stack hint. Under are each threads stack hint:

BoyFriend1

Stack Hint is:

java.lang.Thread.State: TIMED_WAITING (sleeping)

at java.lang.Thread.sleep0(java.base@19.0.1/Native Technique)

at java.lang.Thread.sleep(java.base@19.0.1/Thread.java:465)

at study.synchornized.sameobject.GirlFriend.sing(GirlFriend.java:10)

- locked <0x00000007141e3fe0> (a study.synchornized.sameobject.GirlFriend)

at study.synchornized.sameobject.SameObjectSynchDemo$BoyFriend1.run(SameObjectSynchDemo.java:16)

Locked ownable synchronizers:

- None

Fig: BoyFriend1 thread stack hint exhibiting it acquired the GirlFriend lock

BoyFriend2

Stack Hint is:

java.lang.Thread.State: BLOCKED (on object monitor)

at study.synchornized.sameobject.GirlFriend.rely(GirlFriend.java:19)

- ready to lock <0x00000007141e3fe0> (a study.synchornized.sameobject.GirlFriend)

at study.synchornized.sameobject.SameObjectSynchDemo$BoyFriend2.run(SameObjectSynchDemo.java:25)

Locked ownable synchronizers:

- None

Fig: BoyFriend2 thread stack hint exhibiting it obtained BLOCKED when making an attempt to accumulate the GirlFriend lock

You’ll be able to discover that the ‘BoyFriend2’ thread is blocked, as a result of it’s making an attempt to accumulate the lock ‘0x00000007141e3fe0’ (which is the thing id of ‘GirlFriend’), when it’s making an attempt to invoke the ‘rely()’ technique. Alternatively you may discover ‘BoyFriend1’ acquired the identical lock ‘0x00000007141e3fe0’ and executed the ‘sing()’. ‘BoyFriend1’ wouldn’t launch this lock till it completes executing the ‘sing()’ technique. Thus the ‘BoyFriend2’ thread is stranded and put into BLOCKED state.

Conclusion

On this publish, we learnt how JVM would behave when two threads attempt to execute totally different synchronized strategies on the identical object. You may additionally take into account studying this publish, the place we try to clarify how a JVM would behave when two threads attempt to execute the identical synchronized technique on totally different objects.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments